Chapter 11

Iterators & Generators

11.0 Intro · 11.1 Iterators · 11.2 Generators · 11.3 Pipelines and itertools

← → or Space to navigate · F for fullscreen

Learning Objectives

By the end of this chapter, you will be able to:

  1. Explain Python's iterator protocol and use iter() and next() manually
  2. Use built-in lazy iterators such as enumerate(), zip(), map(), filter(), and reversed()
  3. Build custom iterator classes that implement the iterator protocol
  4. Write generator functions with yield and generator expressions, and delegate to another iterable with yield from
  5. Design multi-step data pipelines using chained generators and itertools tools such as islice and chain

11.1 Iterators

The iteration protocol · iter() / next() · built-in lazy iterators · custom classes

The Iterator Protocol

An iterable can be looped over. An iterator remembers where it is.

# What a for loop does internally
nums = [1, 2, 3]
it = iter(nums)          # get iterator

print(next(it))          # 1
print(next(it))          # 2
print(next(it))          # 3
# next(it) → StopIteration

Built-in lazy iterators

Function What it produces
enumerate(seq) (index, value) pairs
zip(a, b) (a_i, b_i) pairs
map(f, seq) f(x) for each x
filter(pred, seq) elements where pred(x) is truthy
reversed(seq) elements in reverse

All are lazy: values are produced on demand.

Custom Iterator Classes

class Countdown:
    def __init__(self, start):
        self.current = start

    def __iter__(self):
        return self           # the iterator IS the iterable here

    def __next__(self):
        if self.current <= 0:
            raise StopIteration
        value = self.current
        self.current -= 1
        return value

for n in Countdown(5):
    print(n, end=" ")   # 5 4 3 2 1

Built-ins Are Iterators; Iterators Are Single-Use

zip(), enumerate(), map(), filter(), and reversed() return iterators: next() works on them directly, and iter() returns the same object.

pairs = zip(['apple', 'banana'], [1.2, 0.5])
print(iter(pairs) is pairs)   # True
print(next(pairs))            # ('apple', 1.2)
print(list(pairs))            # [('banana', 0.5)]
print(list(pairs))            # []: used up

fruits = ['apple', 'banana']
print(iter(fruits) is iter(fruits))   # False

A custom iterator whose __iter__() returns self keeps its position after a loop:

countdown = Countdown(3)
print(list(countdown))   # [3, 2, 1]
print(list(countdown))   # []

A list hands out a fresh iterator for each loop. To loop over a Countdown again, create a new object.

Skipping Values in __next__()

__next__() can keep looking until it finds a value worth returning, and raise StopIteration only when the data runs out.

class Positives:
    def __init__(self, values):
        self.values = list(values)
        self.index = 0

    def __iter__(self):
        return self

    def __next__(self):
        while self.index < len(self.values):
            value = self.values[self.index]
            self.index += 1
            if value > 0:
                return value      # found one: hand it back
        raise StopIteration       # nothing left

print(list(Positives([4, -1, 7, 0, 3, -2, 8])))   # [4, 7, 3, 8]

11.2 Generators

yield · generator classes · generator expressions · any/all

Generator Functions

A generator function uses yield instead of return. It produces values lazily, one at a time.

def count_up_to(n):
    i = 1
    while i <= n:
        yield i
        i += 1

gen = count_up_to(3)
print(next(gen))   # 1
print(next(gen))   # 2
for val in gen:
    print(val)     # 3

Memory efficiency

import sys

# List: builds everything in memory
lst = [x**2 for x in range(1_000_000)]
print(sys.getsizeof(lst))   # ~8 MB

# Generator: produces one value at a time
gen = (x**2 for x in range(1_000_000))
print(sys.getsizeof(gen))   # ~200 bytes

Use a generator when you iterate once and do not need to store all values.

Watching a Generator Pause

def noisy_gen():
    print("  body starts")
    yield 1
    print("  resumed after yield 1")
    yield 2
    print("  resumed after yield 2, reaching the end")

gen = noisy_gen()
print("generator created")
print("next ->", next(gen))
print("next ->", next(gen))
try:
    next(gen)
except StopIteration:
    print("StopIteration: the body finished")
generator created
  body starts
next -> 1
  resumed after yield 1
next -> 2
  resumed after yield 2, reaching the end
StopIteration: the body finished

Creating the generator runs nothing. Each next() runs only to the next yield, and local variables are kept between calls.

From Iterator Classes to Generators

A generator function replaces the whole Countdown class: Python saves the position for you at each yield.

def countdown(start):
    current = start
    while current > 0:
        yield current
        current -= 1

print(list(countdown(5)))   # [5, 4, 3, 2, 1]

Write __iter__() as a generator to make a reusable iterable: every loop starts a fresh generator.

class CountdownRange:
    def __init__(self, start):
        self.start = start

    def __iter__(self):        # yield makes it a generator
        current = self.start
        while current > 0:
            yield current
            current -= 1

timer = CountdownRange(3)
print(list(timer))   # [3, 2, 1]
print(list(timer))   # [3, 2, 1]

Working with Generator Expressions

A generator is not a list:

  • No len() or indexing. Count with sum(1 for ...).
  • next(gen, default) returns default instead of raising StopIteration.
  • Parentheses. Drop the generator's own parentheses only when it is the only argument.
nums = [4, -1, 7, 0, 3, -2, 8]

print(sum(1 for n in nums if n < 0))           # 2

print(next((n for n in nums if n > 5), None))   # 7
print(next((n for n in nums if n > 100), None)) # None

print(sorted((n for n in nums if n > 0),
             reverse=True))                     # [8, 7, 4, 3]

any() and all() with Generator Expressions

Dropping the brackets avoids building an intermediate list and enables short-circuit evaluation:

data = [4, -1, 7, 0, 3, -2]

# any() stops as soon as it finds True
print(any(x < 0 for x in data))      # True  (stops at -1)

# all() stops as soon as it finds False
print(all(x > 0 for x in data))      # False (stops at -1)

# Common validation patterns
scores = [82, 91, 74, 88, 65]
print(all(s >= 60 for s in scores))  # True: all passed
print(any(s >= 90 for s in scores))  # True: at least one A

11.3 Pipelines and itertools

Pipelines · exhaustion · infinite sequences · yield from · itertools · async bridge · choosing a tool

Generator Pipelines

Each stage consumes the previous one lazily. Nothing runs until the consumer (sum()) pulls values.

def read_rows(text):
    lines = iter(text.splitlines())
    next(lines)                  # skip header
    for line in lines:
        yield line

def parse(rows):
    for row in rows:
        region, product, amount = row.split(",")
        yield {"region": region, "amount": int(amount)}

def in_region(records, region):
    for rec in records:
        if rec["region"] == region:
            yield rec

# SALES: CSV text with a header, "region,product,amount"
east = in_region(parse(read_rows(SALES)), "East")
amounts = (rec["amount"] for rec in east)
print(sum(amounts))   # 425

Iterator exhaustion

print(sum(amounts))   # 0   (already exhausted)
print(list(amounts))  # []

# Fix: rebuild, or materialize once
def east_amounts(text):
    recs = in_region(parse(read_rows(text)), "East")
    return (rec["amount"] for rec in recs)

amounts = list(east_amounts(SALES))
print(sum(amounts), max(amounts))   # 425 210

One record travels through every stage before the next line is read. A finished generator cannot rewind.

yield from

yield from hands part of a generator's work to another iterable. It is shorthand for for item in sub: yield item.

def flatten(nested):
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)   # delegate
        else:
            yield item

print(list(flatten([1, [2, 3], [4, [5, 6]], 7])))
# [1, 2, 3, 4, 5, 6, 7]
def combined(*iterables):
    for it in iterables:
        yield from it

print(list(combined([1, 2], 'ab', range(3))))
# [1, 2, 'a', 'b', 0, 1, 2]

itertools.chain() is the library version of combined().

itertools Highlights

Function Description
islice(it, n) Take first n items
chain(a, b) Concatenate iterables
chain.from_iterable(lists) Flatten one level
count(start, step) Infinite counter
cycle(seq) Repeat sequence infinitely
combinations(seq, r) r-length combos
permutations(seq, r) r-length ordered arrangements
import itertools

# Infinite Fibonacci
def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

first_10 = list(itertools.islice(fib(), 10))
# [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

# Combinations
pairs = list(itertools.combinations("ABCD", 2))
# [('A','B'), ('A','C'), ...]

Never pass an infinite generator to list(), sum(), or max() unbounded. Bound it with islice() or stop with next().

Bridge: Async Iteration

An async generator pauses at yield like a normal generator, and can also pause to wait for I/O without blocking other work.

import asyncio

async def async_count(n):
    for i in range(n):
        await asyncio.sleep(0)   # let other tasks run
        yield i

async def main():
    async for value in async_count(5):
        print(value)             # 0 1 2 3 4

asyncio.run(main())
Term Meaning
async def Declares a coroutine (an async generator if it uses yield)
await Pauses until the awaited task is ready
async for Iterates over an async iterable
Event loop Scheduler that runs coroutines concurrently

Conceptual only: the iterator protocol and yield are the foundation async iteration builds on.

Choosing a Tool

Start with the simplest tool that works:

You need Use Example
Values used several times, or len()/indexing a list prices = [12, 5, 8]
One pass of a simple transform or filter a generator expression sum(p * 1.1 for p in prices)
One pass with several steps, state, or try/except a generator function running_total(numbers)
An object looped over many times a class whose __iter__() is a generator CountdownRange(3)
An iterator with extra methods or inspectable state a class with __iter__() and __next__() Countdown(5)
A standard pattern: slicing, joining, repeating, combining itertools islice, chain, cycle

Chapter 11 Quick Reference

Concept Key syntax / notes
Iterator protocol __iter__ returns self; __next__ returns next value
Manual iteration it = iter(seq) → next(it) → StopIteration
Built-in lazy enumerate, zip, map, filter, reversed
Generator function def f(): yield value
Generator expression (expr for x in seq): lazy, O(1) memory
any / all Drop brackets for short-circuit: any(x > 0 for x in seq)
yield from Delegate to sub-generator
Reusable iterable Class whose __iter__() is a generator
itertools islice, chain, count, cycle, combinations, permutations
Async iteration async def with yield; consume with async for

End of Chapter 11

Next: Chapter 12, APIs

HTTP · requests · JSON · authentication · pagination