Show contents
Chapter 1 of 7 · 20 min
Iterators and generators
By the end of this chapter, you'll be able to
- Explain the iteration protocol: __iter__, __next__ and StopIteration
- Write a generator with yield and predict when it runs
- Chain generators into a lazy pipeline
- Use the itertools tools: islice, groupby, chain, accumulate
The iteration protocol
A for loop works on any iterable object. Behind the scenes, it asks for an iterator with iter(obj), then calls next(iterator) until it raises StopIteration. Any class can play this role:
class Countdown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
self.current -= 1
return self.current + 1
print(list(Countdown(3)))
def countdown(start):
while start > 0:
yield start
start -= 1
gen = countdown(3)
print(next(gen), next(gen))
print(list(gen))
print(list(gen))
[3, 2, 1]
3 2
[1]
[]
The second version does exactly the same in four lines. A function that contains yield is a generator function: calling it runs nothing, it returns a generator. Each next() runs the body up to the next yield, returns the value, then pauses the function, keeping its local variables. When the function ends, the generator raises StopIteration.
Look at the last two lines: a generator can only be gone through once. Once exhausted, it returns nothing more.
A third next() would end the loop and raise StopIteration.
Text description of the animation
- Calling the function doesn't start its body: you get a paused generator, before the first line.
- First next(): the function starts, enters the loop and stops on yield, returning 2.
- print displays 2. The function is suspended, its variable start is still 2.
- Second next(): execution resumes just after the yield, start goes down to 1.
- The loop carries on and stops again on yield, which returns 1.
- A third next() would end the loop and raise StopIteration.
Lazy pipelines
Since a generator only computes a value when it's asked for one, you can chain several: each one consumes the previous one, item by item. Nothing happens until the end of the chain asks for a value:
import itertools
def read_measurements():
# Imagine a sensor or a very big file: the values arrive one by one.
values = [21.5, 22.0, -999, 23.1, 22.8, -999, 24.0, 25.2]
for v in values:
print(f" read {v}")
yield v
def valid(measurements):
for m in measurements:
if m != -999:
yield m
def to_fahrenheit(measurements):
for m in measurements:
yield round(m * 9 / 5 + 32, 1)
pipeline = to_fahrenheit(valid(read_measurements()))
print("Pipeline ready, nothing read yet")
print(list(itertools.islice(pipeline, 2)))
Pipeline ready, nothing read yet
read 21.5
read 22.0
[70.7, 71.6]
islice(pipeline, 2) only asks for two results: only two measurements were read, the other six never. That's the principle of lazy evaluation. A file opened with open() is itself an iterator over lines: for line in file fits straight into such a pipeline.
The itertools toolbox
The itertools module provides ready-made building blocks, all of them lazy:
import itertools
sales = [("Monday", "Dakar", 12), ("Monday", "Lomé", 7), ("Tuesday", "Dakar", 9), ("Tuesday", "Lomé", 11), ("Tuesday", "Cotonou", 4)]
for day, rows in itertools.groupby(sales, key=lambda s: s[0]):
print(day, sum(q for _, _, q in rows))
print(list(itertools.chain([1, 2], (3, 4), "ab")))
print(list(itertools.accumulate([3, 5, 2, 8])))
print(list(itertools.pairwise("ABCD")))
Monday 19
Tuesday 24
[1, 2, 3, 4, 'a', 'b']
[3, 8, 10, 18]
[('A', 'B'), ('B', 'C'), ('C', 'D')]
groupbygroups consecutive items that have the same key;chainputs several iterables end to end;accumulategives running totals;pairwisegives pairs of neighbours, handy for computing differences.
_ is a conventional variable name for "a value I don't need".
Your turn
Worked exercise
Worked exercise: reading a configuration
Write two generators. non_empty_lines(text) produces the text's lines without surrounding spaces, ignoring empty lines and comments (which start with #). numbered(lines, start=1) produces each line preceded by its number right-aligned on 3 characters, in the format 1 | port = 8080. Chain them on a small configuration file.
Hint 1
text.splitlines() splits a text into lines, without the line breaks.Hint 2
enumerate(lines, start=start) numbers, and f"{i:>3}" right-aligns a number on 3 characters.Show the solution and common mistakes
def non_empty_lines(text):
for line in text.splitlines():
line = line.strip()
if line and not line.startswith("#"):
yield line
def numbered(lines, start=1):
for i, line in enumerate(lines, start=start):
yield f"{i:>3} | {line}"
config = """
# Server settings
port = 8080
host = 0.0.0.0
# end
"""
for l in numbered(non_empty_lines(config)):
print(l)
1 | port = 8080
2 | host = 0.0.0.0
Common mistakes:
- Building a list in
non_empty_linesand returning it withreturn: it works here, but every line is kept in memory, and the pipeline is no longer lazy. - Numbering before filtering: the numbers skip (1, 3, 5…) because the ignored lines were counted.
Summary
- 1A for loop calls iter() then next() until StopIteration.
- 2A function with yield returns a generator, which runs in pieces at each next().
- 3Chained generators form a lazy pipeline that's light on memory.
- 4itertools provides islice, groupby, chain, accumulate, pairwise…
- 5A generator can only be gone through once; groupby only groups neighbours.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.