Sub topic 13
Building lazy pipelines from several tools
This chapter assumes you know generator expressions, map, and the basic itertools functions from earlier chapters: chain, islice, takewhile, filterfalse, and accumulate.
The pipeline idea
Each itertools function takes an iterable and returns an iterator. Because the output of one is a valid input for the next, you can connect them in a row. No stage does any work until the final consumer asks for a value. Then one item travels through the whole chain before the next one starts. Memory use stays constant no matter how much data flows through.
A worked pipeline
The input is two "files" of text lines. Some lines are blank or are comments. The goal is to total the numbers in groups of three, stopping once a value of 100 or more appears.
from itertools import batched, chain, filterfalse, takewhile
files = [["5", "", "# note", "12"], ["7", "30", "250", "9"]]
lines = chain.from_iterable(files)
useful = filterfalse(lambda s: not s or s.startswith("#"), lines)
numbers = map(int, useful)
small = takewhile(lambda n: n < 100, numbers)
groups = batched(small, 3)
print(list(map(sum, groups)))This prints [24, 30]. The steps are:
chain.from_iterablejoins both files into one stream.filterfalsedrops blank lines and comments.map(int, ...)converts the remaining strings.takewhilestops at250, so the final9is never read.batchedyields(5, 12, 7)and(30,), andsumturns them into24and30.
batched needs Python 3.12 or later. On older versions, use the islice recipe from the batching chapter.
Naming each stage keeps the pipeline readable. You could also nest the calls, but the named version is easier to debug, because you can inspect any single stage.
Pipelines over infinite sources
Laziness lets a pipeline start from an endless stream, as long as something bounds it at the end.
from itertools import count, islice
squares = (n * n for n in count(1))
evens = (s for s in squares if s % 2 == 0)
print(list(islice(evens, 4)))This prints [4, 16, 36, 64]. count(1) never ends, but islice asks for only four results, so the upstream stages produce just enough values to supply them. Without the bound, list(evens) would run forever.
Combining stages that carry state
Some stages remember earlier items. accumulate keeps a running total, and groupby remembers the current key. They still work in a pipeline, but the order of stages matters. Filtering before accumulate changes the totals. Filtering after it does not.
from itertools import accumulate
readings = [3, -1, 4, -1, 5]
positive_totals = accumulate(r for r in readings if r > 0)
print(list(positive_totals))This prints [3, 7, 12]. The two negative readings are removed first, so they never reach the running sum.
Debugging a pipeline
Do not call list() on an intermediate stage and then keep using it. That consumes the iterator, and the next stage sees nothing. To inspect a stage, use islice(stage, 5) and rebuild the pipeline afterwards. If you need to read one stage twice, build it twice or store its results in a list.
Exercise
Given words = ["a", "bb", "", "ccc", "dd", "e"], write a lazy pipeline that skips empty strings, takes each word's length, and returns the first three lengths. What does it output?
Show answer
from itertools import filterfalse, islice words = ["a", "bb", "", "ccc", "dd", "e"] nonempty = filterfalse(lambda w: not w, words) lengths = map(len, nonempty) print(list(islice(lengths, 3))) It prints [1, 2, 3]. The empty string is dropped, and islice stops after three lengths, so "dd" and "e" are never examined.