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.

5 min readUpdated 2026-11-30
In This Lesson
  • 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 [...] vs Lazy yield Generator

Eager List: [x * 2 for x in range(1M)]

0246...1999998

All 1,000,000 values allocated in RAM immediately.

Lazy Generator: yield x * 2

next(gen)
Pause @ yield → 1 value

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:

python
# 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:

  1. Ask the iterable for a fresh iterator using iter(collection) (which calls collection.__iter__()).
  2. Repeatedly call next(iterator) (which calls iterator.__next__()) until Python raises StopIteration.
python
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!
Iterable vs Iterator

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:

  1. 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).
  2. The first next(gen) runs until yield start, emits 3, and pauses the frame right on that line—preserving start, loop state, and instruction pointer.
  3. The second next(gen) resumes right after yield start, runs start -= 1, loops back to yield start, and emits 2.
  4. When execution falls off the end (or hits return), Python raises StopIteration automatically.
python
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 2

3. 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:

python
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:

python
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

ApproachMemory FootprintReusable?Best Used When
list comprehension [...]O(n) holds all itemsYes (many passes)You need len(x), indexing x[0], or sorting
Generator function yieldO(1) one item at a timeNo (single pass)Streaming files, multi-step pipelines, infinite sequences
Generator expression (...)O(1) one item at a timeNo (single pass)Simple inline transforms fed to sum(), any(), max()
Don't Accidentally Reuse an Exhausted Generator

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

Python 3Try It Live: Generators & Streaming Pipelines
Output

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

Check Your Understanding

What happens immediately when you call gen = my_generator_func() (where the function uses yield)?

Check Your Understanding

What does yield from sub_iterable do inside a generator function?