Python · Module 08: Intermediate & Modern PythonTutorial 22 of 30

8.1 Iterators & Generators (yield & Lazy O(1) Memory)

Process gigabytes of data in 200 bytes of RAM! Understand how Python's for-loop protocol works under the hood, write lazy generator functions with yield, and compare list vs. generator memory.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. The Netflix Streaming Analogy (Eager List vs. Lazy Generator)

Imagine watching a 20 GB 4K movie:

  • A list is like downloading the entire 20 GB file into RAM before you can watch frame 1.
  • A Generator (yield) is like streaming — it computes and hands you one frame at a time, using almost zero RAM!
Visual: Processing 10,000,000 Numbers — Eager `list` vs. Lazy `yield` Generator
List: [n*n for n in range(10_000_000)]~400 MB RAM Allocated Upfront!Builds ALL 10M items before loop startsCan crash with MemoryError on huge logsGenerator: (n*n for n in range(10_000_000))~200 Bytes RAM (Constant O(1)!)Pauses at `yield` — computes 1 item on demandStreams 100 GB files effortlessly!

2. Iterable vs. Iterator Under the Hood

Every Python for x in items: loop secretly calls two built-in functions:

  1. it = iter(items) → asks the Iterable (like a list or string) for an Iterator (a bookmark tracking your current position).
  2. next(it) → pulls the next item one by one until StopIteration signals the end.

3. Writing Generators with yield

A function containing yield instead of return becomes a Generator Function. Every time Python hits yield, it pauses the function, remembers all local variables, hands back the value, and waits until the next next() call!

PYTHON
def countdown(n):
    while n > 0:
        yield n        # Pauses here and hands back n!
        n -= 1

for num in countdown(3):
    print(num)         # 3, 2, 1

# Generator Expression — just replace [...] with (...)!
total = sum(n * n for n in range(1_000_000))  # Uses O(1) constant RAM!

Real-World Superpower: Streaming Huge Log Files

PYTHON
def error_lines(filepath):
    with open(filepath, "r", encoding="utf-8") as f:
        for line in f:
            if "ERROR" in line:
                yield line.strip()   # Streams 50 GB logs without loading into RAM!

Watch Out: Generators are single-use! Once exhausted, looping over the same generator a second time yields nothing — create a fresh generator if you need a second pass.


4. Interactive Trace: Watching yield Pause & Resume State

Tracing a Generator Function with yield
Interactive Line-by-Line Execution Trace · Step 1 of 4
1def gen():
2 yield "first"
3 yield "second"
4→g = gen()
5a = next(g)
6b = next(g)
7print(a, b)
Variables in Memory
g<generator object>generator
Console Output
(nothing printed yet)
What just happened: Calling gen() does NOT run lines 2–3 yet! It returns a paused generator object ready to start.

Quick Quiz: Module 8.1 — Iterators & Generators

Q1.What does calling a generator function `g = my_gen()` immediately return?
Q2.What happens if you loop over the SAME generator object a second time?
Q3.Which syntax creates a lazy generator expression instead of an eager list?

Keep Exploring: Related Lessons & Tools

All Courses →