Skip to content Skip to sidebar Skip to footer

How To Get Back Fo First Element In List After Reaching The End?

For instance: If I am iterating through a Python list ['a','b','c'] how do I get back to element 'a' once I have reached 'c'?

Solution 1:

If you mean to do a loop like if your list was in circle, simply use the modulo operator :

mylist = ["a", "b", "c"]
for i inrange(n): # set n to desired valueprint(mylist[i % len(mylist)])

Solution 2:

If by "get back to element 'a'" you mean to "cycle" back through the list, Then you can use itertools.cycle

from itertools import cycle, islice

data = ["a", "b", "c"]
times_to_iterate = 4

infinite_data = cycle(data)

for element in islice(infinite_data, len(data) * times_to_iterate):
    print(element)

I used islice as it's the same as the builtin slice but for iterators as cycle will iterate forever otherwise. This will iterate through data 4 times.

Post a Comment for "How To Get Back Fo First Element In List After Reaching The End?"