Iterate through a List Multiple times Cyclically starting from the Matching Index

luke picture luke · Dec 21, 2014 · Viewed 12k times · Source

I need to do the following in python. I have a list of strings, list, a string to search for, text, and variable containing the number of elements to print, x. I want to iterate through x no. of consecutive elements of the list, wrapping around to the front of list if necessary.

First I need to find the first element in list that has text as a substring. I will then start with the first element of list after that matched element, and continue to iterate through a total of x consecutive elements of the list, wrapping around if necessary.

How would I do this?

x = 11
text = "string5"
list = ["string1", "string2", "string3", "string4", "string5", "string6", "string7"]

# not sure what to do here...
for elem in list:
    if text in elem:
        #iterate through list, begin with elem and get the next 11 elements
        #once you've reached string7, start over with string1`

In this example I want to end up looking at the following 11 elements:

string6
string7
string1
string2
string3
string4
string5
string6
string7
string1
string2

Answer

tobias_k picture tobias_k · Dec 21, 2014

You can use cycle from itertools, maybe in combination with islice and enumerate.

from itertools import cycle, islice

x = 11
text = "string5"
lst = ["string1", "string2", "string3", "string4", "string5", "string6", "string7"]
for i, elem in enumerate(lst):
    if text in elem:
        next11 = list(islice(cycle(lst), i+1, i+1+x))
        print(next11)
        print(len(next11))

Output:

['string6', 'string7', 'string1', 'string2', 'string3', 'string4', 'string5', 'string6', 'string7', 'string1', 'string2']
11