0
#Python "Iterator problem"
3 Respuestas
+ 5
An iterator cannot truly be reset. We'll have to create a new one, like KrOW showed. You can also use itertools.cycle to make an infinite iterator that keeps cycling through lst1.
from itertools import cycle
lst1 = [4,"potato","solo"]
it = cycle(lst1)
It depends on the task, really. Let us know if any of these fit your requirements :)
+ 10
Exactly, iterators by default are not "traversable back". They have to be recreated on the object for the iteration to "start over".
By Python docs, any custom implementation of iterators should always raise StopIteration when the iterator is exhausted and should continue to do so if it is __next__()-ed consequently :)
+ 6
You have to recreate the iterator for start again from beginning. At example:
lst1 = [4,"potato","solo"]
it = iter(lst1)
i= 0
while i < 20:
try:
print(next(it))
except StopIteration:
it= iter(lst1)
print(next(it))
i+=1