2. Iterators, Generators & Functional Tools
Iterators, Lazy Evaluation & yield Generators
Understand how Python's iterator protocol powers every for loop, and write memory-efficient streaming pipelines using generator functions, yield, and yield from.
- Explain how iter(), next(), and StopIteration drive Python for loops
- Write generator functions with yield to stream data lazily without storing everything in memory
- Compose multiple generators cleanly using yield from
Have you ever wondered why for x in items: works seamlessly on lists, strings, dictionaries, files, and range()? They all speak the same underlying language: the Iterator Protocol.
Understanding iterators and yield generators is what separates scripts that crash with MemoryError on 500 MB files from clean data pipelines that run in a few megabytes of RAM.
Why It Matters: Before vs After
Eager List: [x * 2 for x in range(1M)]
All 1,000,000 values allocated in RAM immediately.
Lazy Generator: yield x * 2
Constant O(1) memory; raises StopIteration when done.
A list builds all 1,000,000 items in RAM up front; a generator pauses on yield and holds only one active frame at a time.
Imagine scanning a multi-gigabyte server log for "ERROR" lines. Building a list upfront stores every matching line in memory before your caller sees the first one:
# Before: eager list — allocates RAM for all matches at once
def collect_errors(lines):
results = []
for line in lines:
if "ERROR" in line:
results.append(line.strip())
return results
# After: lazy generator — holds only ONE line in RAM at a time
def stream_errors(lines):
for line in lines:
if "ERROR" in line:
yield line.strip()If the caller stops after finding the first 5 errors, stream_errors() stops reading immediately instead of processing millions of remaining lines!
1. How for Loops Work Under the Hood
Every for loop in Python translates directly to two iterator-protocol steps:
- Ask the iterable for a fresh iterator using
iter(collection)(which callscollection.__iter__()). - Repeatedly call
next(iterator)(which callsiterator.__next__()) until Python raisesStopIteration.
nums = [10, 20]
it = iter(nums)
print(next(it)) # 10
print(next(it)) # 20
# next(it) now raises StopIteration — which tells `for` to exit cleanly!An iterable (like a list, str, or range) implements __iter__() and can be looped over repeatedly because each iter(my_list) creates a new cursor. An iterator (like a generator or open file) implements both __iter__() (returning self) and __next__(), remembers its current position, and is exhausted after one pass!
2. How yield Pauses and Resumes a Stack Frame
Normal functions use return, which sends back one result and destroys the function's local stack frame (all local variables disappear).
When a function contains yield, Python compiles it into a generator function:
- Calling
gen = countdown(3)does not run line 1 of the body—it returns a suspended generator object holding a frozen stack frame (start = 3). - The first
next(gen)runs untilyield start, emits3, and pauses the frame right on that line—preservingstart, loop state, and instruction pointer. - The second
next(gen)resumes right afteryield start, runsstart -= 1, loops back toyield start, and emits2. - When execution falls off the end (or hits
return), Python raisesStopIterationautomatically.
def countdown(start: int):
print("Starting countdown...")
while start > 0:
yield start
start -= 1
print("Done!")
gen = countdown(3) # Nothing printed yet!
print(next(gen)) # Prints "Starting countdown...", then returns 3
print(next(gen)) # Resumes after yield, returns 23. Composing Pipelines with yield from
When one generator wants to delegate all values from another iterable or sub-generator, use yield from instead of writing an inner for loop:
def flatten(groups):
for group in groups:
yield from group
print(list(flatten([[1, 2], [3, 4], [5]]))) # [1, 2, 3, 4, 5]yield from lets you snap lazy stages together like Lego bricks—nothing executes until the final consumer pulls items:
def numbers():
yield from range(1, 6)
def doubled(stream):
for n in stream:
yield n * 2
print(list(doubled(numbers()))) # [2, 4, 6, 8, 10]Decision Table & Common Pitfalls
| Approach | Memory Footprint | Reusable? | Best Used When |
|---|---|---|---|
list comprehension [...] | O(n) holds all items | Yes (many passes) | You need len(x), indexing x[0], or sorting |
Generator function yield | O(1) one item at a time | No (single pass) | Streaming files, multi-step pipelines, infinite sequences |
Generator expression (...) | O(1) one item at a time | No (single pass) | Simple inline transforms fed to sum(), any(), max() |
If you loop over a generator once—or pass it to list(gen)—its internal frame is finished. Calling sum(gen) a second time silently returns 0! Convert to a list or tuple only when you genuinely need multiple passes, or call the generator function again for a fresh stream.
Try It Yourself in the Playground
Click “Run Code” to execute this snippet right in your browser.
Mini-Challenge: Write a generator function chunked(items, size) that yields slices of length size from items one chunk at a time (e.g., list(chunked([1, 2, 3, 4, 5], 2)) → [[1, 2], [3, 4], [5]]).
Quick Checkpoints
What happens immediately when you call gen = my_generator_func() (where the function uses yield)?
What does yield from sub_iterable do inside a generator function?