Sub topic 10
Pitfalls: exhausted iterators and re-iteration
This chapter assumes you know the iterator protocol (__iter__, __next__, StopIteration), can write generator functions, and can use generator expressions. It covers the most common bug with them: using an iterator after it has been used up.
Iterators are single-use
An iterator remembers only its current position, and it can only move forward. When __next__ raises StopIteration, the iterator is exhausted. Calling next() again keeps raising StopIteration. Nothing resets it.
Generator expressions and generator functions both produce iterators, so they behave this way too:
squares = (x * x for x in range(3))
print(list(squares)) # [0, 1, 4]
print(list(squares)) # []The second list() call gets an empty result and no error. That silence is what makes the bug hard to spot. Any code that loops over the iterator again just runs zero times.
Why a list can be re-iterated
A list is an iterable, not an iterator. Each iter(my_list) call returns a new iterator that starts at the beginning. An iterator's __iter__ returns self, so you get the same half-used object back.
numbers = [1, 2, 3]
print(iter(numbers) is iter(numbers)) # False
it = iter(numbers)
print(iter(it) is it) # TrueCommon ways to hit the bug
Several everyday patterns consume an iterator without making it obvious:
- Calling
list(),sum(),max(),sorted()orlen(list(...))on it, and then using it again. - Partially consuming it with
next()or abreak, then looping again. The loop continues from where it stopped. - Passing the same generator to two functions. The first takes everything and the second gets nothing.
- Testing
if gen:. A generator object is always truthy, even when it would produce no values.
def numbers():
yield from [4, 8, 6]
data = numbers()
print(max(data)) # 8
print(min(data)) # ValueError: min() iterable argument is emptyThe ValueError is the lucky case. sum() over an exhausted iterator returns 0 with no error.
Fixes
You have three main options. Choose based on the size of the data and on whether you can regenerate it.
- Materialize it. Store the values in a list or tuple when the data is small and you need several passes.
- Make an iterable that restarts. Put the generator logic in
__iter__of a class, so each loop gets a fresh generator. - Call the generator function again. Pass the function or its arguments around, not a single generator object.
The second option looks like this:
class Words:
def __init__(self, text):
self.text = text
def __iter__(self):
yield from self.text.split()
w = Words("to be or not")
print(list(w)) # ['to', 'be', 'or', 'not']
print(list(w)) # ['to', 'be', 'or', 'not']Every for loop calls iter(w), which runs __iter__ and builds a new generator. The Words object is reusable even though each generator inside it is not.
Checking your understanding
Exercise
The code below prints a count and then an average. The average line raises ZeroDivisionError. Why, and how would you fix it? values = (n for n in [2, 4, 6]) count = sum(1 for _ in values) average = sum(values) / count
Show answer
The first sum consumes values completely to count items. The second sum(values) then sees an exhausted iterator and returns 0, so the average is 0 (a ZeroDivisionError would only occur if count were 0, and here the result is silently wrong). The fix is to materialize the data once with values = [n for n in [2, 4, 6]], then use len(values) and sum(values). Both passes then see all the items.