Lesson 8: Generator Pipelines and itertools
One generator is useful. Several generators chained together are where the real power lies. A pipeline is a series of small steps, each one a generator that takes values from the previous step, transforms them, and yields them onward. Nothing is stored between steps: a value flows through the whole chain one item at a time, so a pipeline can process a file far larger than your computer's memory, using only a few values at a time. The pattern is the same one that powers Unix pipes, and it is one of the most elegant ideas in Python.
The example below reads a small log file line by line, keeps only the lines that mention an error, and pulls out the error codes. Each stage is a separate generator expression, and the final list() is the only place anything is collected. Because the file object itself is an iterator, the whole file is never loaded into memory at once — the pipeline reads one line, decides whether it matters, and moves on. With a log file of millions of lines, the memory usage stays flat.
# Worked example: imagine errors.log holds lines like
# "2026-11-05 ERROR 404 page not found"
lines = open("errors.log") # a file object is an iterator
errors = (line for line in lines if "ERROR" in line)
codes = (line.split()[2] for line in errors)
print(list(codes)) # for example ['404', '500'] — depends on the file
# The same idea without a file:
numbers = (n for n in range(20) if n % 3 == 0)
doubled = (n * 2 for n in numbers)
print(list(doubled)) # [0, 6, 12, 18, 24, 30, 36]
itertools: the standard library's toolbox
Python's itertools module is a collection of ready-made iterator tools, and it is worth meeting the most useful ones. count() produces an infinite counter, islice() takes a slice of any iterator (including an infinite one), chain() joins several iterables end to end, and groupby() groups consecutive equal items. accumulate() builds running totals, and zip() pairs items from two iterables — though zip is a built-in, not part of itertools. These tools all return iterators, so they compose with your own generators exactly like the pipeline stages above.
A practical tip: when a pipeline grows beyond three or four stages, give each stage a name by writing it as a small generator function instead of an inline expression. Named stages are easier to test, easier to explain, and easier to reuse. The pipeline pattern also teaches a useful habit of mind: think of data as a stream flowing through small, single-purpose steps, rather than as a pile you must hold all at once. That habit will serve you well in the next unit, where decorators and context managers give you similar building blocks for behaviour.
Going further
Pipelines become even more useful when each stage is a named generator function rather than an inline expression. A function called only_errors(lines) that yields the error lines, followed by error_codes(lines) that yields the codes, reads like a description of the job — and each stage can be tested on its own with a small list, which is much harder to do with a chain of inline expressions. The habit of naming stages is the same habit as naming variables well: it turns a clever one-liner into code that a teammate can read, test, and reuse.
The itertools module has a few more members worth meeting once you are comfortable with the basics. takewhile() yields items while a condition holds and then stops; dropwhile() skips items until the condition fails and then yields the rest. cycle() repeats an iterable forever, and repeat() yields the same value again and again. Combined with islice(), these give you precise control over infinite sequences: islice(cycle(["red", "green", "blue"]), 5) produces five colours, cycling as needed. That is the iterator toolbox at its best — small pieces that compose into exactly the behaviour you want.
A practical pipeline to try is processing a real file on your computer — for example, a text file of a few thousand lines. Write a pipeline that reads the file line by line, keeps only the lines longer than eighty characters, and counts how many words those lines contain in total. Use a generator at every stage, and finish with a single sum(). Then change the file to a much larger one and run the same pipeline again: the memory usage stays flat, because no stage ever holds more than one line. That flat memory profile is the signature of a well-built pipeline, and it is the reason this pattern is used for log processing and data work at every scale.
Watch & Learn
One video to watch for this unit, from a trusted educator.
- Python Tutorial: Generators - How to use them and the benefits you receive — Corey Schafer
Corey shows how generators work, why they beat lists for large data, and how yield pauses a function between values.
Key Terms
- Pipeline
- A chain of generator stages, each transforming values from the previous stage, with nothing stored between steps.
- itertools
- A standard-library module of iterator tools: count, islice, chain, groupby, accumulate and more.
- islice()
- Takes a slice of an iterator — the first n items, or a range — without building a list.
- chain()
- Joins several iterables into one continuous iterator, end to end.
- groupby()
- Groups consecutive equal items from an iterable into (key, group) pairs.
- accumulate()
- Yields running totals (or other running combinations) of an iterable.
- zip()
- A built-in that pairs items from two or more iterables, stopping at the shortest.
Discussion Questions
- Why does the log-file pipeline use almost no memory even if errors.log has millions of lines? Trace one line through the stages.
- When would you turn a pipeline stage from an inline generator expression into a named generator function?
- islice() can take the first 10 squares from an infinite generator. Why can't you use ordinary slicing [0:10] on it instead?
Practice Questions
- What is the memory advantage of a generator pipeline over building a list at each stage?
- Write a pipeline that yields the squares of the even numbers from 0 to 9.
- What does
itertools.islice(count(10), 3)produce? - How would you join
[1, 2]and[3, 4]into one iterator? - Why is
open("errors.log")a good first stage for a pipeline?
Show answers
- Only a few values exist at a time; nothing is stored between stages. Each value flows through the whole chain before the next one is produced.
evens = (n for n in range(10) if n % 2 == 0); squares = (n * n for n in evens)The first stage filters, the second transforms; list(squares) gives [0, 4, 16, 36, 64].- An iterator yielding 10, 11, 12. count(10) counts up forever; islice takes just the first three items.
itertools.chain([1, 2], [3, 4]). chain yields 1, 2, 3, 4 in order, without building a new list.- A file object is already an iterator over its lines. It yields one line at a time, so the file is never loaded fully into memory.