18th Nov 2018, 4:32 AM
Fatih Yalçın
Fatih Yalçın - avatar
3 ответов
+ 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 :)
18th Nov 2018, 6:56 AM
Kishalaya Saha
Kishalaya Saha - avatar
+ 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 :)
18th Nov 2018, 7:08 AM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 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
18th Nov 2018, 6:13 AM
KrOW
KrOW - avatar