How Can I Infinitely Loop An Iterator In Python, Via A Generator Or Other?
It's my understanding that using a Generator is the best way to achieve something like this, but I'm open to suggestions. Specifically, one use case is this: I'd like to print som
Solution 1:
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 ...
Solution 2:
Try this-
L = [10,20,30,40]
defgentr_fn(alist):
while1:
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)
10203040102030 ...
Solution 3:
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])
Solution 4:
You can iterate over a list, appending an item to it:
somelist = [item1, item2, item3]
for item in somelist:
somelist.append(item)
do_something()
Post a Comment for "How Can I Infinitely Loop An Iterator In Python, Via A Generator Or Other?"