How can I infinitely loop an iterator in Python, via a generator or other?

You can use module to keep it simple. Just make sure not to start iterating from 0.


my_list = ['sam', 'max']

for i in range(1, 100):
    print(my_list[(i % len(my_list))-1])



Try this-

L = [10,20,30,40]

def gentr_fn(alist):
    while 1:
        for j in alist:
            yield j

a = gentr_fn(L)
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()
print a.next()

>>gentr_fn(x,y)
10 20 30 40 10 20 30 ...

You can use itertools.cycle (source included on linked page).

import itertools

a = [1, 2, 3]

for element in itertools.cycle(a):
    print element

# -> 1 2 3 1 2 3 1 2 3 1 2 3 ...