Lesson 24 of 52Pythonic Python
Iterators and Generators
Understand how for loops really work, write lazy generators with yield, and use itertools like a pro.
A for loop over a 20 GB log file should not need 20 GB of memory. Python handles this with iterators and generators: values produced one at a time, on demand. This is how files, range, zip, map, database cursors and streaming HTTP responses all work, and yield is a classic interview topic.
How a for loop really works
An iterable is anything you can loop over: lists, strings, dicts, files, ranges. An iterator is the object that actually walks through it, remembering where it is. The protocol has two parts:
iter(iterable)calls__iter__and returns an iterator.next(iterator)calls__next__and returns the next value, or raisesStopIterationwhen there are no more.
A for loop is just that, wrapped up for you:
for x in [10, 20]:
print(x)it = iter([10, 20])
while True:
try:
x = next(it)
except StopIteration:
break
print(x)Press Run (⌘ Enter) to see what happens.An iterator is single use. Once exhausted, it stays empty. A list is not an iterator; it is an iterable that hands out a fresh iterator every time you loop.
What does this print?
squares = map(lambda n: n * n, [1, 2, 3]) print(sum(squares)) print(sum(squares))
Generators: functions that pause
Writing a class with __iter__ and __next__ works but is verbose. A generator function is the shortcut: any function containing yield. Calling it does not run the body. It returns a generator object, an iterator. Each next() runs the body until the next yield, hands out that value, and pauses, keeping all its local variables. When the function returns, the generator raises StopIteration.
Press Run (⌘ Enter) to see what happens.The body starts running for the first time.
countdown(3) do on its own?Iterator exhaustion bugs
Single use sounds harmless until it bites in production. The classic shape: a function receives "some rows", checks them, then processes them. With a list that works. Someone later swaps the list for a generator to save memory, and the processing step silently sees fewer rows, or none. No exception, no warning, just a wrong number.
Press Run (⌘ Enter) to see what happens.any stops as soon as it finds 12, so it has already consumed 5 and 12. sum gets only what is left: 7. The same trap hides in other places:
x in genconsumes items up to and including the match. Everything after it is still there, everything before it is gone.- Logging or printing a generator for debugging (
print(list(rows))) empties it for the real code below. - Passing one iterator to two consumers, such as
zip(it, it). That one is sometimes a deliberate trick for pairing items, but it confuses readers. - A generator stored on an object (
self.items = (x for x in ...)) that a second method loops over again. The second loop finds nothing.
The fixes are boring, which is good. If you need more than one pass, materialise once with rows = list(rows) at the top of the function and say so in a comment. If the data is too big for that, restructure into one pass that computes everything at once. itertools.tee can split one iterator into several, but it buffers every item one copy has seen and the other has not, so if one copy runs far ahead, you are back to holding the whole list in memory. In function signatures, type the parameter as Iterable[int] when you loop once and as Sequence[int] when you need len, indexing or two passes. The annotation tells the caller what they may pass.
What does this print?
gen = (n for n in range(10)) print(5 in gen) print(list(gen))
Iterable classes vs iterator classes
When you write your own collection, you choose which of the two roles your class plays, and getting it wrong reproduces the exhaustion bug inside your own type.
An iterator class has __next__ and an __iter__ that returns self. That return self is what makes it single use: every for loop gets the same object, already partly walked. An iterable class has an __iter__ that returns a new iterator every call. The easiest way to do that is to make __iter__ a generator function, so each call creates a fresh generator.
Press Run (⌘ Enter) to see what happens.The rule of thumb: containers (things that hold data, like Playlist, a query result you already fetched, a matrix) should be iterables. Iterators are for things that are naturally one pass: a network stream, a database cursor, a file. That is also why open() returns an iterator: the operating system file position really does move forward.
The last line shows a handy check. For any iterator, iter(x) is x is true. For a re-iterable container it is false. Some libraries use exactly that test to refuse a one-shot iterator where they need two passes.
Report class has __iter__ that returns self and a __next__ that walks self.rows. A nested loop for a in report: for b in report: produces far fewer pairs than expected. What is the cleanest fix?Lazy evaluation saves memory
A list holds every element in memory at once. A generator holds only its current state, no matter how many values it will produce. That is called lazy evaluation: values are computed only when someone asks.
Press Run (⌘ Enter) to see what happens.The list uses megabytes; the generator uses about two hundred bytes, whatever the range. The syntax difference is only the brackets: [...] builds a list, (...) builds a generator expression. When you pass one straight into a function, you can drop the extra parentheses: sum(n * n for n in nums).
Laziness also lets you work with infinite sequences and build pipelines where each stage pulls one item at a time from the previous one:
Press Run (⌘ Enter) to see what happens.Nothing runs until the final for pulls. At any moment only one line is in flight through the whole pipeline.
Generator pipelines for real log processing
The toy pipeline above scales up into one of the most useful patterns in everyday Python work. A support ticket says checkout is slow. You have a few gigabytes of JSON log lines and want to know which paths are failing. Write each step as a small generator function that takes an iterable and yields results, then plug them together.
Nothing happens when you build the pipeline. Work starts only when the consumer at the end asks for an item.
Press Run (⌘ Enter) to see what happens.Look at the second query. next(..., None) stops the whole pipeline after the first match, so the bad line 3 is never even read, and the skip message does not print. On a real file that is the difference between reading 2 lines and 20 million. In a real script, io.StringIO becomes open(path, encoding="utf-8"), and for compressed logs gzip.open(path, "rt", encoding="utf-8") returns the same kind of line iterator, so nothing else changes.
Why this design holds up at work:
- Each stage is testable alone.
parse(["{}", "junk"])is a one-line unit test with a plain list as input. - Stages compose. Adding "only the last hour" is one more small function, not an edit to a 60-line loop.
- Memory stays flat. The pipeline uses roughly the memory of one record plus whatever the final consumer keeps.
The trade-off is debugging: a stack trace from inside a pipeline points at whichever stage was running, and there is no list to inspect halfway. When something looks wrong, pull a few items with list(islice(stage, 5)) on a fresh pipeline. For very hot paths, the per-item function-call overhead of many tiny stages can matter; Profiling and Making Python Fast shows how to measure before you merge stages.
yield from
yield from other yields every value from another iterable, one by one. It is the clean way for one generator to delegate to another, and it shines in recursive generators.
Press Run (⌘ Enter) to see what happens.What does this print?
def inner(): yield 1 yield 2 def outer(): yield 0 yield from inner() yield 3 print(list(outer()))
Generators can return a value
A generator may end with return something. That value is not yielded. Python attaches it to the StopIteration that ends the generator, as StopIteration.value. A for loop or list() catches that StopIteration and throws the value away, which is why you rarely see it. The place it matters is yield from: the expression yield from sub() evaluates to the sub-generator's return value, so a delegating generator can get a summary back from its helper.
Press Run (⌘ Enter) to see what happens.The last part is a real bug pattern with a safety net. Calling next(it) inside a generator on an empty iterator raises StopIteration inside the generator body. In old Python, that silently ended the generator, which could truncate output with no error at all. Since Python 3.7 (PEP 479), a StopIteration that escapes a generator body is turned into RuntimeError: generator raised StopIteration. If you see that message, look for a bare next() inside a generator, and either pass a default, next(it, None), or catch StopIteration and return.
What does this print?
def gen(): yield 1 return 99 def outer(): result = yield from gen() yield result print(list(gen())) print(list(outer()))
send, throw and close
A generator is a paused function, and you can talk to it while it is paused. You need to recognise these methods more than write them: they appear in older coroutine code, in framework internals, and in interview questions about how async grew out of generators.
gen.send(value)resumes the generator and makes the pausedyieldexpression evaluate tovalue.next(gen)is the same asgen.send(None). You must advance a new generator to its firstyieldbefore sending a real value, often called priming it.gen.throw(exc)resumes the generator by raisingexcat the pausedyield. The generator can catch it and carry on, or let it propagate.gen.close()raisesGeneratorExitat the pausedyield, sofinallyblocks andwithblocks inside the generator run. Python also calls it when an unfinished generator is garbage collected.
Press Run (⌘ Enter) to see what happens.close has a practical consequence. A generator that opens a file inside with open(...) and is abandoned halfway (say, you break out of the loop after the first match) still has the file open until the generator is closed or garbage collected. In CPython, reference counting usually does that immediately, but other implementations, and generators caught in reference cycles, can hold the file much longer. When cleanup timing matters, close it yourself: contextlib.closing(gen) or an explicit gen.close() in a finally.
These methods are also what make @contextmanager work, which you will use in the next lesson but one, Context Managers. The decorator turns your generator into an object whose __enter__ calls next() to run up to the yield, and whose __exit__ either calls next() again (no error) or calls throw() with the exception from the with body, so your try/except/finally around the yield sees it.
A thirty-line contextmanager, built from send and throw
This is a simplified version of what contextlib does. The real one also checks that the generator yields exactly once and gives clearer errors, but the core is exactly this.
Press Run (⌘ Enter) to see what happens.Notice that the ValueError did not escape. The generator caught it and finished, so the context manager reported it as handled. Re-raise inside the except (a bare raise after the rollback) if callers must still see the error. That is usually what you want for a real transaction.
Native async def coroutines started life as generators driven by send, and they still share the same machinery underneath: an event loop resumes a paused coroutine much as send resumes a generator. Async and Await covers the modern syntax; you never need send to write async code today.
Order what happens when you run avg = averager(); next(avg); avg.send(10).
- Tap the steps below in the right order.
itertools: the iterator toolbox
The itertools module is a set of fast, lazy building blocks. These are the ones worth knowing by heart:
| Function | What it yields | Example |
|---|---|---|
count(start) | start, start+1, ... forever | IDs, infinite indexes |
islice(it, n) | the first n items (slicing for iterators) | take from an infinite stream |
chain(a, b) | everything from a, then from b | join iterables without copying |
groupby(it, key) | runs of consecutive items with the same key | group sorted data |
product(a, b) | every pair, like nested loops | grid coordinates |
permutations(it, r) | every ordering | brute-force small searches |
combinations(it, r) | every subset of size r, order ignored | pick 2 of n |
pairwise(it) | (a, b), (b, c), ... | differences between neighbours |
batched(it, n) | tuples of up to n items (3.12+) | send rows in chunks |
Press Run (⌘ Enter) to see what happens.One trap: groupby only groups consecutive equal keys. Sort by the same key first, or you get the same key several times. The next lesson, functools, itertools and operator, goes through these by job (sliding windows, running totals, cutting streams) and covers the rest of the module.
Pick the itertools function for each job.
Chunk any iterable
Write a generator chunks(items, n) that yields lists of up to n consecutive items from any iterable. The last chunk may be shorter. If n < 1, raise ValueError.
list(chunks([1, 2, 3, 4, 5], 2)) # [[1, 2], [3, 4], [5]]
list(chunks("abc", 3)) # [["a", "b", "c"]]It must be lazy: it should work on an infinite iterator like itertools.count() as long as the caller only takes a few chunks. So do not call list(items) or len(items). Write it yourself rather than calling itertools.batched.
Flatten with yield from
Write a generator flatten(nested) that yields every non-list value from an arbitrarily nested list, in order, left to right.
list(flatten([1, [2, [3, [4]]], [], 5])) # [1, 2, 3, 4, 5]
list(flatten(["ab", ["cd"]])) # ["ab", "cd"] (strings are values, not lists)Use recursion and yield from.
- iterable
- Anything with
__iter__, which returns an iterator. Lists, strings, dicts and files are iterables. - iterator
- An object with
__next__that produces values one at a time and raisesStopIterationat the end. - generator
- An iterator created by a function containing
yield; it pauses at eachyieldand keeps its state. - generator expression
(expr for x in it): a lazy, one-pass version of a list comprehension.- yield from
- Yields every value from another iterable, delegating to it.
- lazy evaluation
- Computing values only when they are requested, so memory use stays constant.
- exhaustion
- An iterator that has produced all its values stays empty; looping again yields nothing, without an error.
- StopIteration.value
- Where a generator's
returnvalue goes;yield fromevaluates to it. - send / throw / close
- Generator methods that resume it with a value, with an exception, or with
GeneratorExitto run its cleanup.