08 / 22 · Data Structures
Iteration, comprehensions and generators
The iterator protocol behind every for loop, iterables against iterators, list, dict and set comprehensions and generator expressions, generator functions whose frames pause at yield, yield from, the itertools essentials, and lazy data pipelines with batching.
Control flow · Functions · Lists and tuples · Dictionaries and sets
On this page 9
The previous note built its dictionaries with loops: a for over the words, one insertion per pass. The same for walked over lists, strings, ranges, the keys of a dictionary and, in the control flow note, the characters of a string, and each of these containers is laid out differently in memory. This note asks how one statement can walk all of them. The answer is a small protocol, two methods that any object can provide. On top of it the note builds the shorter forms for making lists, dicts and sets, comprehensions, and the objects that produce items only when asked, generators, which let a program process a file or a stream larger than memory. It ends with the pipelines of lazy stages that feed batches to the training loops of the ML courses.
Baseline: a loop over positions#
A loop can walk a list by position:
i = 0
while i < len(xs):
print(xs[i])
i += 1
This needs two things the object may not have. It needs indexing, and a set, a dictionary’s keys or a file have no position . It needs a length known in advance, and a stream of sensor readings or the lines of a network response have none. And it needs the items to exist already: to loop over the squares of a million numbers this way, they must first be computed and stored. Python’s for asks for none of this.
The iterator protocol#
The rule (Python documentation, iterator types):
- An iterable is an object whose type defines
__iter__, which returns an iterator.iter(obj)calls it. (Sequences that define only__getitem__with indices from 0 are accepted too, an older form.) - An iterator is an object whose type defines
__next__, which returns the next item or raisesStopIterationwhen there are none, and__iter__, which returns the iterator itself.next(it)calls__next__. for x in obj: bodyis equivalent to
it = iter(obj)
while True:
try:
x = next(it)
except StopIteration:
break
body
The calls can be made by hand:
>>> xs = [10, 20]
>>> it = iter(xs)
>>> it
<list_iterator object at 0x1017c1e40>
>>> next(it)
10
>>> next(it)
20
>>> next(it)
Traceback (most recent call last):
...
StopIteration
The iterator protocol: what a for loop does
- The loop calls
iter(xs)once.list.__iter__creates a newlist_iterator, a small object that holds a reference to the list and an index, starting at 0. - Before the first pass, the loop calls
next(it). The iterator readsxs[0], advances its index to 1 and returns 10, which is bound tox; the body runs. - The second
next(it)returns 20, and the body runs withx = 20. - The third finds the index equal to
len(xs)and signalsStopIteration. The loop catches it and ends; it never reaches the program.
What the interpreter runs. The bytecode of a for loop in CPython 3.14.7 has one instruction for each half of the protocol:
>>> import dis
>>> def show(xs):
... for x in xs:
... print(x)
...
>>> dis.dis(show)
1 RESUME 0
2 LOAD_FAST_BORROW 0 (xs)
GET_ITER
L1: FOR_ITER 14 (to L2)
STORE_FAST 1 (x)
3 LOAD_GLOBAL 1 (print + NULL)
LOAD_FAST_BORROW 1 (x)
CALL 1
POP_TOP
JUMP_BACKWARD 16 (to L1)
2 L2: END_FOR
POP_ITER
LOAD_CONST 0 (None)
RETURN_VALUE
GET_ITER replaces xs on the stack by iter(xs). FOR_ITER calls next on it and either pushes the item, which STORE_FAST binds to x, or, when the iterator is exhausted, jumps past the loop to L2. For built-in iterators such as list_iterator the interpreter checks exhaustion directly, without creating a StopIteration object at all; the exception is the protocol’s contract, and the fast path is an optimization of it (How CPython runs code reads bytecode in detail).
Writing an iterator. A class becomes an iterator by defining the two methods. A countdown:
>>> class Countdown:
... def __init__(self, start):
... self.n = start
... def __iter__(self):
... return self
... def __next__(self):
... if self.n == 0:
... raise StopIteration
... self.n -= 1
... return self.n + 1
...
>>> list(Countdown(3))
[3, 2, 1]
list() ran the same protocol as for. Methods with double underscores, which Python calls on your behalf, are the subject of the data model note; an object without __iter__ is not iterable, and for x in 42: raises TypeError: 'int' object is not iterable.
Iterables and iterators are not the same#
The rule. Calling iter() on a container returns a new iterator each time, so a list can be looped over any number of times, and two loops over it, even nested ones, do not disturb each other. Calling iter() on an iterator returns the same iterator, which remembers its position: once exhausted, it stays exhausted.
>>> nums = [1, 2, 3]
>>> it = iter(nums)
>>> iter(it) is it, iter(nums) is iter(nums)
(True, False)
>>> list(it)
[1, 2, 3]
>>> list(it)
[]
>>> pairs = zip('ab', [1, 2])
>>> dict(pairs)
{'a': 1, 'b': 2}
>>> dict(pairs)
{}
The mistake. Many built-ins return iterators rather than lists: zip, map, filter, enumerate, reversed, open files, and every generator. Using one of them twice gives nothing the second time, and no error says so: the second dict(pairs) above is silently empty. To recognize it, look for a value that is used in two places and comes from one of these functions. The cure is to materialize it once, pairs = list(zip(...)), or to create it again where it is needed. The rule also explains a design choice: range(n) is not an iterator but a lazy sequence, with its own __iter__, and can be looped over again and indexed.
Comprehensions#
The rule. A list comprehension [expr for x in iterable if cond] builds the list that this loop would build:
result = []
for x in iterable:
if cond:
result.append(expr)
The if part is optional, and several for and if clauses can follow one another, nested in the order written. Braces give a set comprehension {expr for x in it} or a dict comprehension {key: value for x in it}, and parentheses give a generator expression (expr for x in it), which builds nothing and produces the items one at a time when iterated (Python language reference, §6.2.4–6.2.8).
>>> [x * x for x in range(6)]
[0, 1, 4, 9, 16, 25]
>>> [x * x for x in range(6) if x % 2 == 0]
[0, 4, 16]
>>> {w: len(w) for w in ['to', 'be', 'or']}
{'to': 2, 'be': 2, 'or': 2}
>>> {len(w) for w in ['to', 'be', 'not']}
{2, 3}
>>> (x * x for x in range(6))
<generator object <genexpr> at 0x10631e0c0>
>>> sum(x * x for x in range(6))
55
>>> [(i, j) for i in range(2) for j in 'ab']
[(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]
A generator expression that is the only argument of a call needs no extra parentheses: sum(x * x for x in range(6)). The two for clauses in the last line run as nested loops, the first outermost, the same order as the loop they replace.
Scope. The loop variable of a comprehension is local to it and does not overwrite a name outside:
>>> x = 'outer'
>>> [x for x in range(3)]
[0, 1, 2]
>>> x
'outer'
Until Python 3.11 CPython implemented this by compiling every comprehension into a hidden function and calling it. Since 3.12 list, dict and set comprehensions are inlined into the surrounding code, which saves the call, while the loop variable stays isolated (PEP 709); generator expressions still get a function of their own, because they must outlive the line that created them.
When to use which. A comprehension is the clearest form for building a collection from another one, and on this machine it is slightly faster than the loop with append (28 ms against 31 ms for a million squares, CPython 3.14.7, Apple M1), because it skips looking up result.append on every pass. A comprehension that needs three nested clauses or a long condition is better written as a loop, and a comprehension used only for its side effects, [print(x) for x in xs], builds a list of None for nothing. Python 3.15, released in October 2026, adds unpacking inside comprehensions, [*xs for xs in lists] to flatten one level (PEP 798).
Generator functions and yield#
A class iterator must store its state in attributes and rebuild its position on every __next__. A generator function keeps the state in ordinary local variables.
The rule. A function whose body contains yield is a generator function. Calling it runs none of its body; it returns a generator object, which is an iterator. Each next() on it runs the body from where it last stopped until the next yield expr, which hands expr to the caller and suspends the function; local variables and the position are kept. When the body finishes, or reaches return value, next() raises StopIteration with that value attached (Python language reference, yield expressions).
>>> def countdown(n):
... print('start')
... while n > 0:
... yield n
... n -= 1
... print('done')
... return 'finished'
...
>>> g = countdown(2)
>>> g
<generator object countdown at 0x10631e0c0>
>>> next(g)
start
2
>>> next(g)
1
>>> next(g)
done
Traceback (most recent call last):
...
StopIteration: finished
'start' was not printed when countdown(2) was called, only at the first next. Between the calls the function was not running at all; it resumed at n -= 1 with n still 2.
A generator: a frame that pauses
countdown(2)creates a generator object. Inside it is a frame: the function’s local variables (n = 2) and its position in the bytecode, set to the start. No line of the body has run.next(g)resumes the frame. It printsstart, enters the loop and reachesyield n. The value 2 goes to the caller, and the frame is suspended at that point.- The next
next(g)continues right after theyield:n -= 1makesn1, the loop test passes, andyield nhands out 1. - The third
next(g)decrementsnto 0, the loop ends,doneis printed andreturn 'finished'closes the generator. The caller receivesStopIteration('finished'); aforloop would simply end.
Why it works: a frame that lives on the heap. An ordinary call creates a frame for the function’s locals and destroys it when the function returns. A generator’s frame belongs to the generator object instead, so it survives between calls; yield saves the instruction position in it and returns to the caller, and next resumes the interpreter at that position (Shaw). The state can be inspected:
>>> import inspect
>>> def gen():
... yield 1
...
>>> g = gen()
>>> inspect.getgeneratorstate(g)
'GEN_CREATED'
>>> next(g)
1
>>> inspect.getgeneratorstate(g), g.gi_frame.f_lineno
('GEN_SUSPENDED', 2)
>>> list(g)
[]
>>> inspect.getgeneratorstate(g)
'GEN_CLOSED'
Laziness, measured. A generator computes an item only when asked and forgets it after handing it out, so its memory does not depend on how many items it produces. Summing a million squares through a list comprehension first stores all of them; through a generator expression, never more than one:
A list holds every item, a generator one frame
The list costs about 40 bytes per item, 40 MB for a million: an 8-byte slot plus a share of the list’s spare slots, and an int object of 28 or 32 bytes (squares above need a second 30-bit digit, as the values note showed); the generator costs about 400 bytes at any size. Both sums took the same time, 35 ms. Laziness also makes infinite sequences possible, since only the items asked for are ever computed, and it lets a search stop early:
>>> import itertools
>>> evens = (n for n in itertools.count() if n % 2 == 0)
>>> next(evens), next(evens), next(evens)
(0, 2, 4)
>>> list(itertools.islice(evens, 4))
[6, 8, 10, 12]
>>> next(n for n in range(10**12) if n * n > 50)
8
The last line looks at nine numbers out of a trillion. itertools.count() never ends, and islice takes a bounded slice of any iterator, which plain slicing cannot do, since an iterator has no indices.
Two mistakes. A generator is an iterator, so it is used up after one pass, as in the previous section. And a StopIteration raised by accident inside a generator, for example by a bare next() on an exhausted iterator, would silently end the generator early; since Python 3.7 it is turned into a RuntimeError: generator raised StopIteration instead (PEP 479). Use return to end a generator.
yield from: delegating to another generator#
The rule. yield from sub inside a generator yields every item of the iterable sub, one by one, as if each had been yielded directly, and evaluates to the value that sub returned (PEP 380). It is how a generator hands part of its work to another one; a recursive generator needs it to pass on the items of its recursive calls:
>>> def flatten(items):
... for item in items:
... if isinstance(item, list):
... yield from flatten(item)
... else:
... yield item
...
>>> list(flatten([1, [2, [3, 4]], 5]))
[1, 2, 3, 4, 5]
>>> def inner():
... yield 1
... return 'inner done'
...
>>> def outer():
... result = yield from inner()
... yield result
...
>>> list(outer())
[1, 'inner done']
Without yield from, the recursive call flatten(item) would only create a generator object and discard it. For a plain iterable yield from xs is shorthand for for x in xs: yield x; for a sub-generator it also forwards values sent in with send() and exceptions thrown in with throw(), the machinery from which Python’s coroutines grew before async and await replaced it (concurrency note).
The tools that consume and combine iterators#
enumerate and zip. enumerate(it, start=0) yields pairs of a counter and an item, which replaces the loop over range(len(xs)). zip(a, b, …) yields tuples of the items at the same position and stops at the shortest input, silently. Since Python 3.10, strict=True turns a length mismatch into an error (PEP 618), and since 3.14 map accepts strict=True too:
>>> list(enumerate(['a', 'b'], start=1))
[(1, 'a'), (2, 'b')]
>>> list(zip('abc', [1, 2]))
[('a', 1), ('b', 2)]
>>> list(zip('abc', [1, 2], strict=True))
Traceback (most recent call last):
...
ValueError: zip() argument 2 is shorter than argument 1
Pairing features with labels that have drifted out of step, one row dropped from one of them, is a bug that zip hides and strict=True catches at once.
itertools. The module holds building blocks that take iterators and return iterators, all lazy (Python documentation, itertools):
>>> list(itertools.chain([1, 2], 'ab'))
[1, 2, 'a', 'b']
>>> list(itertools.accumulate([3, 1, 4, 1, 5]))
[3, 4, 8, 9, 14]
>>> list(itertools.pairwise('abcd'))
[('a', 'b'), ('b', 'c'), ('c', 'd')]
>>> list(itertools.batched(range(7), 3))
[(0, 1, 2), (3, 4, 5), (6,)]
>>> list(itertools.product('ab', [0, 1]))
[('a', 0), ('a', 1), ('b', 0), ('b', 1)]
>>> [(k, len(list(g))) for k, g in itertools.groupby('aaabccaa')]
[('a', 3), ('b', 1), ('c', 2), ('a', 2)]
chain joins iterables end to end, accumulate gives running totals, pairwise (3.10) gives consecutive pairs, batched (3.12) cuts an iterable into tuples of , the last possibly shorter, or raises ValueError for a short last batch when given strict=True (3.13). product replaces nested loops; a grid search over hyperparameters is product(learning_rates, batch_sizes). groupby groups consecutive equal keys only, as the two separate runs of 'a' show; sort by the key first to group all of them.
Data pipelines#
Generators compose. Each stage takes an iterator and returns one, and nothing happens until the last stage asks for an item; then each stage pulls exactly one item from the stage before it. A pipeline of lazy stages handles a file of any size in the memory of a single batch. The pattern, with numbers made up for the example:
def lines(): # stage 1: a source, here an endless stream of "index,value" lines
for i in itertools.count():
yield f"{i},{random.gauss(0, 1):.3f}"
def parse(rows): # stage 2: text to (index, value) tuples
for row in rows:
i, x = row.split(",")
yield int(i), float(x)
records = (r for r in parse(lines()) if r[1] > -2) # stage 3: drop outliers
for batch in itertools.islice(itertools.batched(records, 32), 2):
... # stage 4: two batches of 32
The Code section counts the lines the source produced: 66. Two batches of 32 records needed 64 lines that passed the filter and 2 that did not, and not one line more, although the source is infinite.
Where the ML courses use it. The training loops of the ML courses take minibatches: a few dozen examples per gradient step, a fresh order every epoch (Stochastic and adaptive optimizers). PyTorch’s DataLoader is an iterable in exactly this sense: each for batch in loader calls its __iter__, which returns an iterator that draws indices, loads the examples and stacks them into a batch (PyTorch and automatic differentiation). Corpora too large for memory are tokenized by generators that read one document at a time. Two things a pure stream cannot do cheaply, and real pipelines handle explicitly: shuffling, which needs random access or a buffer of items to shuffle within, and a second pass, which needs the source to be read again, since an iterator is used up.
What changed#
| Loop over positions (the baseline) | for with the iterator protocol | Generator | |
|---|---|---|---|
| Needs from the object | indexing and a length | __iter__, and an iterator with __next__ | nothing: it is written as a function |
| Works on | sequences | anything iterable: sets, dicts, files, streams | produces its own items |
| Items | must exist in advance | may be computed on demand | computed on demand, one frame in memory |
| Infinite sequences | impossible | possible | natural (itertools.count) |
| Passes | any number | any number for containers, one for iterators | one |
Limitations#
- One pass, forward only. An iterator cannot be rewound, indexed or asked for its length;
itertools.teebuffers items to give several independent passes, at the cost of the memory it saves elsewhere. - Laziness moves errors. A generator pipeline raises an error when the bad item is pulled, which may be far from where the generator was created, and the traceback shows the consumer’s line as well as the stage that failed.
- Overheads. Every
nexton a Python-level generator is a resumption of a frame, a few tens of nanoseconds; for numerical work on millions of numbers, NumPy’s whole-array operations avoid per-item Python code altogether (NumPy arrays). - Not covered.
send()andthrow()on generators beyond a mention, asynchronous generators andasync for, which the concurrency note treats, and context managers built from generators, which the next note introduces.
What you should remember#
for x in objcallsiter(obj)once, thennext()untilStopIteration. In bytecode:GET_ITER, thenFOR_ITERper pass.- An iterable makes iterators; an iterator is its own iterable and is used up after one pass.
zip,map,enumerate, files and generators are iterators. - Comprehensions build lists, dicts and sets in one expression with their own loop variable; a generator expression builds nothing and yields items lazily.
- A generator function returns a generator; each
nextresumes its frame to the nextyield. Its memory is one frame, whatever the number of items: about 400 bytes against 40 MB for a list of a million squares. yield fromdelegates to a sub-iterator and returns its value.enumerate,zip(strict=True),itertools.islice,chain,pairwise,batchedandproductcover most loops.- A pipeline of generators processes a stream in the memory of one batch, which is how data reaches a training loop.
Code#
The script checks each claim in turn: a hand-written loop against for and the iteration instructions in its bytecode, exhaustion, a class iterator against a generator, the four kinds of comprehension, the memory of a list against a generator measured with tracemalloc, yield from, the iteration tools, and a lazy pipeline that counts how many lines it actually produced. It needs only the standard library, has a fixed seed and runs in under a second with python -I iteration.py. The byte counts are those of a 64-bit build and vary slightly between runs and platforms.
"""Iteration, comprehensions and generators: the protocol, laziness and pipelines (Python 3.14)."""
import dis
import inspect
import itertools
import random
import tracemalloc
# 1. A for loop is iter() once, then next() until StopIteration
def by_hand(xs):
out, it = [], iter(xs)
while True:
try:
x = next(it)
except StopIteration:
break
out.append(x)
return out
def with_for(xs):
return [x for x in xs]
print(by_hand("abc") == with_for("abc"), [i.opname for i in dis.get_instructions(with_for) if "ITER" in i.opname])
# 2. An iterable gives a fresh iterator each time; an iterator is used up
nums = [1, 2, 3]
it = iter(nums)
print(list(it), list(it), list(nums), list(nums))
# 3. The same sequence from a class with __next__ and from a generator function
class Countdown:
def __init__(self, start): self.n = start
def __iter__(self): return self
def __next__(self):
if self.n == 0:
raise StopIteration
self.n -= 1
return self.n + 1
def countdown(n):
while n > 0:
yield n
n -= 1
g = countdown(3)
print(list(Countdown(3)), inspect.getgeneratorstate(g), next(g), inspect.getgeneratorstate(g), list(g))
# 4. Comprehensions: list, dict, set and generator expression
words = ["to", "be", "or", "not", "to", "be"]
print([len(w) for w in words], {w: len(w) for w in words}, {len(w) for w in words}, sum(len(w) for w in words))
# 5. Laziness, measured: peak memory of a list against a generator over a million items
def peak(f):
tracemalloc.start()
f()
p = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
return p
n = 10**6
print(f"list: {peak(lambda: sum([x * x for x in range(n)])):,} bytes, "
f"generator: {peak(lambda: sum(x * x for x in range(n))):,} bytes")
# 6. yield from delegates to a sub-generator
def flatten(items):
for item in items:
if isinstance(item, list):
yield from flatten(item)
else:
yield item
print(list(flatten([1, [2, [3, 4]], 5])))
# 7. enumerate, zip(strict=True), pairwise, batched
print(list(enumerate("ab", start=1)), list(itertools.pairwise("abcd")), list(itertools.batched(range(7), 3)))
try:
list(zip("abc", [1, 2], strict=True))
except ValueError as err:
print("ValueError:", err)
# 8. A lazy pipeline: records -> parse -> filter -> batches; only the lines needed are produced
random.seed(0)
produced = 0
def lines():
global produced
for i in itertools.count():
produced += 1
yield f"{i},{random.gauss(0, 1):.3f}"
def parse(rows):
for row in rows:
i, x = row.split(",")
yield int(i), float(x)
records = (r for r in parse(lines()) if r[1] > -2) # drop outliers below -2
for batch in itertools.islice(itertools.batched(records, 32), 2):
print(len(batch), round(sum(x for _, x in batch) / len(batch), 3))
print("lines produced:", produced)
# Output with CPython 3.14.7 on an Apple M1, macOS (arm64); byte counts vary slightly:
# True ['GET_ITER', 'FOR_ITER', 'POP_ITER']
# [1, 2, 3] [] [1, 2, 3] [1, 2, 3]
# [3, 2, 1] GEN_CREATED 3 GEN_SUSPENDED [2, 1]
# [2, 2, 2, 3, 2, 2] {'to': 2, 'be': 2, 'or': 2, 'not': 3} {2, 3} 13
# list: 40,447,072 bytes, generator: 408 bytes
# [1, 2, 3, 4, 5]
# [(1, 'a'), (2, 'b')] [('a', 'b'), ('b', 'c'), ('c', 'd')] [(0, 1, 2), (3, 4, 5), (6,)]
# ValueError: zip() argument 2 is shorter than argument 1
# 32 -0.067
# 32 0.18
# lines produced: 66
Next#
Every source of items in this note lived inside the program. Real data comes from files: a CSV of measurements, a JSON configuration, a corpus of text. Reading them is iteration again, since a file object is an iterator over its lines, but it adds what this note could ignore: bytes that must be decoded into text, resources that must be released, and operations that fail because a file is missing or malformed. The next note covers exceptions, the with statement and files.
References#
- Python documentation (3.14): Iterator types and Generator types; The Python Language Reference, §6.2.4–6.2.8 displays and comprehensions, yield expressions and the
forstatement;itertools;inspect.getgeneratorstate;dis(GET_ITER,FOR_ITER);tracemalloc; the Functional Programming HOWTO. - G. Ewing. PEP 380 — Syntax for Delegating to a Subgenerator. 2009.
- C. Angelico, G. van Rossum. PEP 479 — Change StopIteration handling inside generators. 2014.
- B. Bucher. PEP 618 — Add Optional Length-Checking To zip. 2020.
- C. Meyer. PEP 709 — Inlined comprehensions. 2023.
- PEP 798 — Unpacking in Comprehensions. Python 3.15.
- L. Ramalho. Fluent Python, 2nd ed. O’Reilly, 2022. Ch. 2 (list comprehensions and generator expressions) and ch. 17 (iterators, generators, and classic coroutines).
- D. Beazley, B. K. Jones. Python Cookbook, 3rd ed. O’Reilly, 2013. Ch. 4 (iterators and generators), including generator pipelines.
- A. Shaw. CPython Internals. Real Python, 2021 (generators and their frames).