Learning navigation

Code with Animation

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.

Python8 min readConcept 23 of 24

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.

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.

Select Generator Protocol:
# Generator function:
def count_up():
yield 1 # Suspends state
yield 2 # Suspends state
yield 3 # StopIteration next
# Caller drive:
gen = count_up()
val = next(gen) # Returns 1
LAZY GENERATOR & YIELD STATE MACHINECURRENT ITERATION: step 1 of 3Call next(gen) ➔YIELD 1● Active YieldYIELD 2PendingYIELD 3PendingSTATE: GEN_SUSPENDED (Frame preserved in memory)Yielded value: 1 | Local instruction pointer frozen until next()STEP 1: Function paused at yield 1, state frozen in memory✓ Calling next() resumes execution right where it was paused
★ Python Rule: Generators cannot be indexed or sliced (gen[0] raises a TypeError). Furthermore, once exhausted, a generator cannot be reset; call the generator function again to instantiate a fresh stream.

Check yourself

Pick an answer to lock it in, then read why. Getting one wrong is part of how it sticks.

  1. 1What does calling a function that contains the 'yield' keyword immediately return?
  2. 2What happens when you call next() on a generator that has already finished executing its code?
  3. 3Why 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)])`?

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.

Done with this concept?

Mark it complete to track your progress. No login needed.