# Generators & The Lazy yield Protocol

> Master Python generators and the yield keyword: stream infinite or massive datasets with constant O(1) memory, pause and resume execution states, implement custom iterators, and eliminate out-of-memory crashes.

Subject: Python | Lesson 23 of 24 | 8 min read
Interactive lesson: https://codewithanimation.in/python/generators
Previous: [Comprehensions: List, Dict & Set Expressions](https://codewithanimation.in/python/list-comprehensions.md) | Next: [Decorators & Function Wrappers](https://codewithanimation.in/python/decorators.md)

## Lazy Evaluation vs Eager Materialization

Standard functions compute their entire result and return it in a single batch (eager evaluation). If you build a list with 10 million elements, Python must allocate memory for all 10 million items simultaneously before returning.

A generator function produces values lazily on demand. Any function that includes the `yield` keyword becomes a generator factory.

When called, a generator function does not run to completion; instead, it immediately returns a generator iterator object that yields values one by one only when asked.

## Constant Memory: Megabytes vs Bytes

The primary architectural benefit of generators is their tiny, constant O(1) memory footprint.

A list of 1,000,000 integers consumes approximately 8.5 megabytes of RAM. A generator producing the exact same 1,000,000 numbers consumes merely 104 bytes - the size of the generator state object itself.

Because values are produced on the fly and discarded after processing, generators allow Python programs to process multi-gigabyte log files and streaming server data without triggering out-of-memory crashes.

## The yield Lifecycle: Suspension, next(), and StopIteration

When code requests the next value using `next(gen)` (or inside a `for` loop), Python executes the generator function until it encounters a `yield <value>` statement.

At that exact point, Python pauses the function, freezes its local variables and instruction pointer in memory, and returns the yielded value to the caller.

On the subsequent `next(gen)` call, execution resumes immediately after the `yield` statement with all local state intact. When the generator reaches the end of the function, it raises a `StopIteration` exception, which Python `for` loops automatically intercept to cleanly end the iteration.

## Common mistake: The Exhaustion Trap: Consumed Only Once

Generators are single-use streams. Once a generator has yielded all its values, it is exhausted. Running a second `for` loop or calling `next()` over an exhausted generator produces nothing (or raises `StopIteration`).

Additionally, generators do not support random access or indexing: `gen[0]` raises `TypeError: 'generator' object is not subscriptable`.

If you need to reuse the dataset multiple times or access arbitrary indices, convert the generator explicitly to a list using `list(gen)`, or reconstruct the generator.

## Tip: Chain Generator Expressions into Zero-Memory Pipelines

Combine generator expressions using parentheses `()` to build composable data processing pipelines: `lines = (line.strip() for line in open('log.txt'))`, followed by `errors = (l for l in lines if 'ERROR' in l)`. Data streams through this pipeline item by item without intermediate memory buffers.

## Try it: Lazy Generator Memory & Execution State Machine

Step through execution with next() calls. Contrast the tiny 104-byte generator state machine against an eager list RAM allocation, watching execution freeze and resume at each yield point.

The animation is on the lesson page and is not part of this text version: https://codewithanimation.in/python/generators

## Check yourself

### Question 1

What does calling a function that contains the 'yield' keyword immediately return?

- A. A generator iterator object without executing the function body yet
- B. The first value yielded by the function
- C. A frozen tuple containing all yielded items
- D. None

Correct answer: A

Calling a generator function does not run the code immediately. It creates and returns a generator iterator object. Code execution only begins when next() is called on that generator object.

- Why not B: The function body does not begin running until next() is called.
- Why not C: Generators do not materialize items in a tuple or list.
- Why not D: It returns an active generator iterator object.

### Question 2

What happens when you call next() on a generator that has already finished executing its code?

- A. It raises a StopIteration exception
- B. It loops back and yields the first value again
- C. It returns None indefinitely
- D. It raises an IndexError

Correct answer: A

When a generator reaches the end of its function body or encounters a return statement, it raises StopIteration. Python for loops catch this exception automatically to terminate iteration cleanly.

- Why not B: Generators are single-use streams and do not rewind automatically.
- Why not C: An exhausted generator raises StopIteration on subsequent next() calls.
- Why not D: StopIteration is the protocol signal used by Python iterators.

### Question 3

Why does evaluating `sum(x**2 for x in range(1_000_000))` consume almost no memory compared to `sum([x**2 for x in range(1_000_000)])`?

- A. The generator expression streams each squared number one by one into sum() without creating an intermediate 8MB list in RAM
- B. The generator expression executes in a multi-threaded C subprocess
- C. The range function deletes each element from memory before the list is passed to sum()
- D. Python stores generator expressions in CPU L1 cache instead of system RAM

Correct answer: A

The generator expression with parentheses produces each number on demand, passes it to sum(), and immediately frees it from memory. The list comprehension with square brackets must fully allocate and store all 1,000,000 items in heap memory simultaneously before sum() can start.

- Why not B: Generator expressions run synchronously on the single main thread.
- Why not C: A list comprehension must allocate all elements simultaneously before sum() starts.
- Why not D: Generators are Python heap objects with an internal frame of just ~104 bytes.

## Remember this

- Functions with yield return generator iterators that evaluate elements lazily on demand.
- Generators consume constant O(1) memory (~104 bytes) regardless of whether they produce 10 items or 10 billion items.
- Calling next(gen) advances execution to the next yield and freezes local variable state.
- Generators are single-pass streams and cannot be indexed (gen[0] fails) or re-iterated once exhausted.
- Chain generator expressions with () for high-performance memory-efficient pipelines.
