Lesson contents

Python — Lazy generators and iterator state

Use a generator function to filter readings without building a second collection.

A simple example

Resume a generator

  1. Start with Call numbers()
  2. Do this Read each yield
  3. Result 1 → 2
The for loop asks the generator for one value at a time. After the second yield the generator finishes.
lesson.py
def numbers():
    yield 1
    yield 2

for n in numbers():
    print(n)
Output
1
2
Advertisements

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.

First value taken: 4. Still in the stream: 7. Remaining sum: 7.
Read a stream once

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
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))
Output
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.

The Python Tutorial

Related tags

  • Python
  • generators
  • yield
  • iterators