Why can’t I iterate twice over the same iterator? How can I “reset” the iterator or reuse the data?

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, which can be traversed as many times as needed. For example:

data = list(data)

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 over in turn:

for e in it1:
    print("first loop")

for e in it2:
    print("second loop")

Leave a Comment