Skip to content
devtoolbox.cc

Python · Chapter 18 of 21

Python iterators, generators, itertools and context managers

14 min study · Examples checked with Python 3.14 and 3.15 ·

Every for loop you have written relies on one small protocol: ask an object for an iterator, then ask the iterator for the next value until it says it’s done. Understanding that protocol lets you write your own lazy producers with yield, process files larger than memory in pipelines, and use the itertools module well. The same chapter covers context managers, the protocol behind with, because generators are also the easiest way to write them.

Iterables and iterators

An iterable is anything you can loop over: a list, a string, a file, a dictionary. Calling iter() on it returns an iterator, an object that remembers its position and hands out the next item when you call next().

lessons = ["Variables", "Loops", "Functions"]
it = iter(lessons)
print(next(it), next(it))            # Variables Loops
print(next(it), next(it, "done"))    # Functions done

print(list(it))                      # []  (the iterator is used up)
print(list(lessons))                 # ['Variables', 'Loops', 'Functions']

When an iterator runs out, next() raises StopIteration, which a for loop catches silently; passing a default to next() returns that instead. A list can produce a new iterator any number of times, but an iterator itself is single-use. That distinction causes a classic bug: code that calls len(list(items)) to count a generator and then loops over it finds nothing left. If you need to go over data twice, keep it in a list or recreate the iterator.

Generators: functions that pause

A function containing yield is a generator function. Calling it doesn’t run the body; it returns a generator object, an iterator whose body runs one step each time a value is requested:

def countdown(start: int):
    print("starting")
    while start > 0:
        yield start
        start -= 1
    print("finished")

gen = countdown(3)
print("created")
print(next(gen))       # prints "starting", then 3
print(list(gen))       # [2, 1], after printing "finished"

The output order shows the laziness: created comes before starting, because the body only starts on the first next(). Each yield hands out a value and freezes the function, local variables included, until the next request. When the function ends, iteration stops. Generators are ideal for sequences that are large, expensive or endless, since only one value exists at a time.

One consequence of the delayed start is that validation inside a generator body is delayed too: countdown("x") succeeds, and the error appears only when someone starts iterating. If arguments must be checked immediately, validate in an ordinary function that then returns the generator.

Generator expressions

A generator expression looks like a list comprehension in parentheses and produces values lazily:

scores = [72, 85, 91, 64]
squares = (s * s for s in scores)
print(sum(squares), sum(squares))            # 24786 0
print(sum(s * s for s in scores))            # 24786 (parentheses can be shared)
print(any(s < 65 for s in scores), max(s for s in scores if s < 90))  # True 85

Use one when the result is consumed once by a function such as sum, any, all, max or "".join. Like any iterator it is used up after one pass, which is why the second sum is 0. A list comprehension is better when you need the results more than once or need their length. any and all stop as soon as they know the answer, so they may not consume the whole input.

Streaming pipelines

Generators chain naturally: each stage consumes the previous one and yields to the next, so a file is processed one line at a time from end to end.

from pathlib import Path

def lines(path: Path):
    with path.open(encoding="utf-8") as f:
        for line in f:
            yield line.rstrip("\n")

def errors(rows):
    for row in rows:
        level, _, message = row.partition(" ")
        if level == "ERROR":
            yield message

log = Path("app.log")
log.write_text("INFO started\nERROR timeout\nWARN slow\nERROR disk full\n", encoding="utf-8")
for number, message in enumerate(errors(lines(log)), start=1):
    print(number, message)
# 1 timeout
# 2 disk full

Only one line is in memory at any moment, whether the log has four lines or forty million. The with inside lines keeps the file open while the generator is paused and closes it when the generator finishes. If the consumer stops early (say, after the first error), the file stays open until the generator is closed or garbage-collected; call gen.close(), or keep the with in the consumer, when that matters. yield from other_iterable hands out every item of another iterable, which is a shortcut for a for loop that yields.

itertools: ready-made building blocks

The itertools module has fast, lazy tools for common iteration patterns:

import itertools as it

print(list(it.islice(it.count(start=1, step=5), 4)))       # [1, 6, 11, 16]
print(list(it.chain(["intro"], ["loops", "classes"])))       # ['intro', 'loops', 'classes']
print(list(it.batched(range(1, 8), 3)))                      # [(1, 2, 3), (4, 5, 6), (7,)]
print(list(it.pairwise([10, 13, 19])))                       # [(10, 13), (13, 19)]
print(list(it.accumulate([30, 45, 25])))                     # [30, 75, 100]

sessions = [("Mon", 30), ("Mon", 15), ("Tue", 40), ("Mon", 10)]
for day, group in it.groupby(sorted(sessions), key=lambda s: s[0]):
    print(day, sum(minutes for _, minutes in group))
# Mon 55
# Tue 40

count counts forever and islice takes a slice of any iterator, which makes infinite generators safe to use. chain joins iterables, batched (Python 3.12+) groups items into fixed-size tuples, handy for sending records to an API in chunks, pairwise yields neighbours and accumulate running totals. groupby groups consecutive items with the same key, so the data must be sorted by that key first; without the sorted, the last Monday session would form a separate group. product, permutations and combinations round out the module.

Context managers and the with statement

A with statement guarantees that cleanup runs when the block ends, normally or through an exception. Any object with __enter__ and __exit__ methods works with it; the quickest way to write one is a generator decorated with contextlib.contextmanager:

from contextlib import contextmanager
import time

@contextmanager
def timer(label: str):
    start = time.perf_counter()
    try:
        yield
    finally:
        print(f"{label}: {time.perf_counter() - start:.3f}s")

with timer("import"):
    total = sum(range(1_000_000))
print(total)    # 499999500000 (after the timing line)

Code before yield runs on entering the block, code after it on leaving; the try/finally makes sure the cleanup runs even if the block raises. Whatever the generator yields becomes the value of as in with timer(...) as t:. The standard library uses the same protocol for files, locks (chapter 19), database transactions, tempfile.TemporaryDirectory and contextlib.suppress. Whenever something must be released, reach for a context manager rather than try/finally scattered through your code.

Practice

Write a generator valid_scores(lines) that yields integers from text lines, skipping blank lines and lines that are not whole numbers from 0 to 100. Feed it the lines of a file, keep only passes (60 or more) with a generator expression, and compute the count and the total in one loop so the file is read once. Then use itertools.batched to print the passing scores in groups of three.

Answer check: for the lines "72", "", "x", "101", "58", "90", the valid scores are 72, 58 and 90, and the passes are 72 and 90, so count 2 and total 162. Calling list() on the generator a second time returns []; call valid_scores again for a fresh pass.

Summary

Iterables produce iterators; iterators are single-use. Generators run lazily, pause at each yield and keep their local state, which makes memory-friendly pipelines easy. Use generator expressions for one-pass consumers, itertools for common patterns (sort before groupby), and context managers, often written with @contextmanager, for anything that needs cleanup.

All Python chapters