Python — Lazy generators and iterator state
Use a generator function to filter readings without building a second collection.
A simple example
Resume a generator
- Start with Call numbers()
- Do this Read each yield
- Result 1 → 2
def numbers():
yield 1
yield 2
for n in numbers():
print(n)
1 2
Consume an iterator one value at a time
yield suspends the function between results. next consumes 4 from the shared iterator. sum resumes from that position and consumes only the remaining value, 7.
A volunteer takes the first valid count from a shared stream of readings. That call consumes 4, leaving only 7 for the subsequent sum. Reading from the same iterator continues from its current position.
Run the example
Python 3.8 or later. Run these commands from the directory containing the example.
python3 lesson.py
def positives(readings):
for value in readings:
if value > 0:
yield value
stream = positives([-1, 4, 7])
print(next(stream))
print(sum(stream))
4 7
The first call to next consumes 4. The sum sees only the remaining 7 because both operations share the same iterator.
Try it yourself
What would a second sum on stream return?
Check your answer
Zero. The first sum exhausted the generator. Call the generator function again to create a new iterator.