An iterator can only be consumed once. For example:
lst = [1, 2, 3]
it = iter(lst)
next(it)
# => 1
next(it)
# => 2
next(it)
# => 3
next(it)
# => StopIteration
When the iterator is supplied to a for
loop instead, that last StopIteration
will cause it to exit the first time. Trying to use the same iterator in another for loop will cause StopIteration
again immediately, because the iterator has already been consumed.
A simple way to work around this is to save all the elements to a list (for example, by doing data = list(data)
), which can be traversed as many times as needed.
If the iterator would iterate over many elements, however, it’s a better idea to create independent iterators using tee()
:
import itertools
it1, it2 = itertools.tee(data, 2) # create as many as needed
Now each one can be iterated in turn:
for e in it1:
print("doing this one time")
for e in it2:
print("doing this two times")