Iteration, comprehensions and generators
The iterator protocol behind every for loop, iterables against iterators, comprehensions, generators and yield, yield from, the itertools essentials and a lazy pipeline that feeds batches to a training loop.
One loop for many containers
The topic Dictionaries and sets built its word counts with a loop: one for over the words of the corpus, one insertion per pass. The same for has already walked over lists, strings, ranges, the keys of a dict and the members of a set. Yet these objects are laid out very differently. A list is an array of references, and a dict or a set is a hash table with empty slots in it.
A loop over positions shows why that is a puzzle. It needs the object to answer xs[i]:
vocab = {"cat", "mat", "sat"}
i = 0
while i < len(vocab):
print(vocab[i])
i += 1The last line of the traceback says why it fails:
TypeError: 'set' object is not subscriptableA set has no position 0. A dict has keys instead of positions, so counts[0] looks for the key 0 and raises KeyError: 0, while for w in counts simply walks the keys. The loop over positions also needs a length known in advance, and a stream of sensor readings has none. And it needs every item to exist before the loop starts.
A for loop asks for none of this. This topic opens the small protocol behind it. On top of the protocol it builds two tools: comprehensions, which build collections in one expression, and generators, which compute items only when asked. The running example is the piece of code that feeds a training loop, a data loader that yields batches:
for batch in batches(examples, 32):
... # one gradient step per batchBy the end of the topic batches is written, and it works on data that does not fit in memory.
The iterator protocol
Iteration is a conversation between the loop and an iterator. The loop asks once for an iterator with iter(obj). Then it asks for the next item with next(it), again and again. When there are no items left, the iterator answers with the exception StopIteration.
The calls can be made by hand:
losses = [0.9, 0.7]
it = iter(losses)
print(it)
print(next(it))
print(next(it))
print(next(it))The first three lines of output are below; the address differs from run to run. The fourth next ends the script with a traceback whose last line is StopIteration.
<list_iterator object at 0x105ff8760>
0.9
0.7The list_iterator is a small separate object. It holds a reference to the list and an index that starts at 0. Each next reads the item at the index and moves the index on.
So for x in losses: with a body is the same as the loop below. The try/except pair catches the one exception that means "no more items"; the topic Files and exceptions treats exceptions in full.
it = iter(losses)
while True:
try:
x = next(it)
except StopIteration:
break
print(x) # the body of the for loopAn object that iter() accepts is iterable. Its type defines the special method __iter__, which returns an iterator. An iterator's type defines __next__, which next() calls. The topic The data model shows how our own classes define them. An object without __iter__ is not iterable, and for x in 42: fails with TypeError: 'int' object is not iterable.
Every consumer of items speaks this protocol, not only for: list(), sum(), max(), sorted(), dict(), zip() and unpacking such as a, b, c = losses. CPython even has one bytecode instruction for each half. In 3.14, [i.opname for i in dis.get_instructions(f) if "ITER" in i.opname] for a function f with a for loop gives ['GET_ITER', 'FOR_ITER', 'POP_ITER']. GET_ITER calls iter, FOR_ITER calls next on every pass, and POP_ITER drops the iterator at the end. The topic How CPython runs code reads bytecode in detail.
Iterables and iterators
A list and its iterator behave differently when asked for an iterator. A list gives a new iterator each time. An iterator gives itself, and it remembers its position:
losses = [0.9, 0.7, 0.6]
it = iter(losses)
print(iter(it) is it, iter(losses) is iter(losses))
print(list(it), list(it))
print(list(losses), list(losses))True False
[0.9, 0.7, 0.6] []
[0.9, 0.7, 0.6] [0.9, 0.7, 0.6]So a list can be looped over any number of times, even by two nested loops at once. An iterator is used up after one pass and stays used up.
Many built-ins return iterators, not lists. zip(a, b) yields tuples of items at the same position. enumerate(xs) yields pairs of a counter and an item, so list(enumerate(["the", "cat"])) is [(0, 'the'), (1, 'cat')]. The same holds for map, filter, reversed and every generator below. Reusing one of them is a classic bug in a training loop:
features = [[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]]
labels = [0, 1, 1]
pairs = zip(features, labels)
for epoch in range(2):
seen = 0
for x, y in pairs:
seen += 1
print("epoch", epoch, "examples", seen)epoch 0 examples 3
epoch 1 examples 0The second epoch trains on nothing, and no error says so. Look for a value that is used in two places and comes from one of these functions. Then either materialize it once, pairs = list(zip(features, labels)), or create it again where it is needed, inside the epoch loop.
range is the exception that proves the rule. range(3) is not an iterator but a lazy sequence. iter(range(3)) makes a fresh iterator each time, and the range can also be indexed, range(3)[1] == 1, and measured, len(range(3)) == 3.
Comprehensions
Building a list with a loop and append is so common that Python has an expression for it. 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. Braces give a set comprehension or, with key: value, a dict comprehension. The vocabulary from the topic Dictionaries and sets, which maps each word to an id, took a loop there. Here it is one line: dict.fromkeys(words) drops repeats and keeps the order of first appearance, so the ids come out the same.
words = ["the", "cat", "sat", "on", "the", "mat"]
print([len(w) for w in words])
print([w for w in words if len(w) > 2])
print({len(w) for w in words})
vocab = {w: i for i, w in enumerate(dict.fromkeys(words))}
print(vocab)
print([(i, c) for i in range(2) for c in "ab"])[3, 3, 3, 2, 3, 3]
['the', 'cat', 'sat', 'the', 'mat']
{2, 3}
{'the': 0, 'cat': 1, 'sat': 2, 'on': 3, 'mat': 4}
[(0, 'a'), (0, 'b'), (1, 'a'), (1, 'b')]Several for clauses nest in the order they are written, the first one outermost, as in the loops they replace. So the last line runs c over "ab" once for each i.
The loop variable of a comprehension is local to it. After for w in words: the name w still refers to the last word, but a comprehension leaves an outer w alone. Since Python 3.12 CPython compiles list, dict and set comprehensions inline, without a hidden function call (PEP 709), and the variable stays isolated all the same.
A comprehension is the clearest way to build one collection from another. Three nested clauses or a long condition read better as a loop. A comprehension used only for its side effects, [print(w) for w in words], builds a list of None for nothing.
Generators and yield
Parentheses instead of brackets give a generator expression, (len(w) for w in words). It builds nothing: printing it shows <generator object <genexpr> at 0x...>. It produces the items one at a time when iterated, so sum(len(w) for w in words) is 17 without a list ever existing. A generator expression that is the only argument of a call needs no extra parentheses.
A loop that is too long for one expression becomes a generator function: a function whose body contains yield. Calling it runs none of the body. It returns a generator object, which is an iterator:
def countdown(n):
print("start")
while n > 0:
yield n
n -= 1
print("done")
g = countdown(2)
print(g)
print(next(g))
print(next(g))
print(next(g, "exhausted"))<generator object countdown at 0x104162400>
start
2
1
done
exhaustedNothing was printed by countdown(2) itself. The first next ran the body up to yield n, handed 2 to the caller and suspended the function. The second next resumed right after the yield, with n still 2. The third ran off the end of the body, so the generator raised StopIteration. Here next was given a default, which it returns instead of raising.
This works because an ordinary call destroys its frame, the local variables and the current position, when it returns. A generator's frame belongs to the generator object and survives between calls. inspect.getgeneratorstate(g) shows it going from GEN_CREATED through GEN_SUSPENDED to GEN_CLOSED.
Now the data loader of the running example can be written:
def batches(examples, size):
batch = []
for x in examples:
batch.append(x)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
print(list(batches(range(7), 3)))
print(list(batches((w for w in words if len(w) > 2), 2)))With words from the previous block, it prints:
[[0, 1, 2], [3, 4, 5], [6]]
[['the', 'cat'], ['sat', 'the'], ['mat']]batches never indexes and never asks for a length, so it takes any iterable, another generator included. After each yield it binds a new list rather than clearing the old one, because the caller still holds a reference to the batch it received. To end a generator early, use return. A stray StopIteration inside a generator, from a bare next on an exhausted iterator, becomes RuntimeError: generator raised StopIteration (PEP 479).
Laziness
A generator computes an item when asked and forgets it once handed out. Its memory does not depend on how many items it produces. tracemalloc from the standard library measures the peak memory of the two ways to sum a million squares:
import tracemalloc
def with_list(n):
return sum([x * x for x in range(n)])
def with_generator(n):
return sum(x * x for x in range(n))
for f in (with_list, with_generator):
tracemalloc.start()
f(10**6)
peak = tracemalloc.get_traced_memory()[1]
tracemalloc.stop()
print(f.__name__, f"{peak:,} bytes")On a 64-bit CPython 3.14.7 on macOS this printed the lines below; the exact bytes vary slightly between builds:
with_list 40,447,744 bytes
with_generator 408 bytesThe list costs about 40 bytes per item: an 8-byte reference plus an int object of 28 or 32 bytes. The generator costs a few hundred bytes at any size. For a corpus or a dataset bigger than memory, that difference decides whether the program runs at all.
Laziness also makes infinite sequences possible, since only the items asked for are ever computed. itertools.count() counts up forever. itertools.islice(it, k) takes the first k items of any iterator, which plain slicing cannot do, because an iterator has no positions.
import itertools
evens = (n for n in itertools.count() if n % 2 == 0)
print(next(evens), next(evens), next(evens))
print(list(itertools.islice(evens, 4)))
print(next(n for n in range(10**12) if n * n > 50))0 2 4
[6, 8, 10, 12]
8The islice went on from where the three next calls stopped. The last line finds the answer after looking at nine numbers out of a trillion: the search stops as soon as next has its item.
yield from and itertools
A generator can hand part of its work to another iterable. yield from sub yields every item of sub in turn, as if each were yielded directly. A recursive generator needs it, since a bare recursive call only creates a generator object and drops it:
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])))[1, 2, 3, 4, 5]yield from also evaluates to the value the sub-generator returned, and it forwards the send and throw methods, the machinery Python's coroutines grew from (the topic Concurrency: threads, processes and asyncio).
Most loops do not need hand-written generators at all. The itertools module holds lazy building blocks that take iterators and return iterators:
import itertools
print(list(itertools.chain([1, 2], "ab")))
print(list(itertools.accumulate([3, 1, 4, 1, 5])))
print(list(itertools.pairwise([0.9, 0.7, 0.6])))
print(list(itertools.batched(range(7), 3)))
print(list(itertools.product([0.1, 0.01], [16, 32])))
print([(k, len(list(g))) for k, g in itertools.groupby("aaabccaa")])[1, 2, 'a', 'b']
[3, 4, 8, 9, 14]
[(0.9, 0.7), (0.7, 0.6)]
[(0, 1, 2), (3, 4, 5), (6,)]
[(0.1, 16), (0.1, 32), (0.01, 16), (0.01, 32)]
[('a', 3), ('b', 1), ('c', 2), ('a', 2)]chain joins iterables end to end. accumulate gives running totals, and pairwise gives consecutive pairs, such as the change in loss between epochs. batched (Python 3.12) is our batches with tuples instead of lists. product replaces nested loops: a grid search over learning rates and batch sizes is one product. groupby groups only consecutive equal keys, as the two separate runs of 'a' show; sort by the key first to group them all.
One more rule from the same family. zip stops at the shortest input without a word, so features and labels that have drifted out of step pair up wrongly. zip(features, labels, strict=True) turns a length mismatch into ValueError: zip() argument 2 is shorter than argument 1.
A data pipeline
Generators compose into a pipeline. Each stage takes an iterator and returns one. Nothing happens until the last stage asks for an item, and then each stage pulls exactly one item from the stage before it. A source that counts the lines it produces shows this. Here it is an endless stream of "x,y" lines:
import itertools
produced = 0
def read_lines():
global produced
for i in itertools.count():
produced += 1
yield f"{i % 7 - 1},{i % 2}"
def parse(lines):
for line in lines:
x, y = line.split(",")
yield float(x), int(y)The pipeline drops the rows with negative x and asks for two batches of 4:
kept = ((x, y) for x, y in parse(read_lines()) if x >= 0)
for batch in itertools.islice(itertools.batched(kept, 4), 2):
print(batch)
print("lines produced:", produced)((0.0, 1), (1.0, 0), (2.0, 1), (3.0, 0))
((4.0, 1), (5.0, 0), (0.0, 0), (1.0, 1))
lines produced: 10Eight rows passed the filter and two did not, and not one line more was read, although the source never ends. Memory holds one batch at a time, whatever the size of the data.
A training loop makes several passes, one per epoch, and a generator gives only one. So the loader must be created anew for each epoch, exactly as with zip above:
rows = ["0.5,1", "0.1,0", "0.9,1", "0.3,0", "0.7,1"]
def loader(lines, size):
return itertools.batched(parse(lines), size)
once = loader(rows, 2)
for epoch in range(2):
print(epoch, [len(b) for b in once], [len(b) for b in loader(rows, 2)])0 [2, 2, 1] [2, 2, 1]
1 [] [2, 2, 1]PyTorch's DataLoader, which the Deep Learning course uses, follows the same rule. It is an iterable, not an iterator: each for batch in loader gets a fresh iterator, and with shuffle=True a new order of examples. Shuffling is the one thing a pure stream cannot do cheaply, since it needs random access or a buffer.
So far the source was a list or a counter inside the program. Real data comes from files, and a file object is an iterator over its lines. Files add what this topic could ignore: bytes to decode into text, a resource to release, and lines that break the pipeline. A row "n/a,1" raises ValueError: could not convert string to float: 'n/a' in parse, at the moment that row is pulled. The next topic, Files and exceptions, deals with exceptions, the with statement and files.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.