11.3. Pipelines and itertools#

Generators become most useful when you chain them. This section builds lazy pipelines from the generator functions and expressions in Generators, explains what happens when an iterator runs out, produces infinite sequences, delegates with yield from, and surveys more of itertools. It ends with a bridge to async iteration and a guide to choosing among the tools in this chapter.

11.3.1. Generator Pipelines#

A generator pipeline is a chain of small generators in which each stage consumes the output of the stage before it. Every stage does one job: one produces raw records, the next parses them, the next filters them, and a final consumer such as sum(), list(), max(), or a for loop reduces the stream to a result.

The stages are lazy. Building the chain only creates generator objects; no record is read, parsed, or filtered until the consumer asks for its first value. Each request then travels back up the chain, and one value flows down the chain, through every stage or until a filter drops it, before the next value is produced.

read_rows  ->  parse  ->  in_region  ->  (amount for ...)  ->  sum()
 raw lines     dicts      East only      numbers               total

11.3.1.1. Building a Pipeline#

The pipeline below totals the East region’s sales from a small block of CSV-style text. The text is an inline string, so you can run the example without any files. Each stage is a generator function that takes an iterable and yields new values, and the last stage is a generator expression that picks out the amount field.

SALES = """region,product,amount
East,apple,120
West,banana,85
East,cherry,210
West,apple,40
East,banana,95"""

def read_rows(text):
    """Stage 1: yield one raw line at a time, skipping the header."""
    lines = iter(text.splitlines())
    next(lines)                      # skip the header row
    for line in lines:
        yield line

def parse(rows):
    """Stage 2: turn each line into a dict with a numeric amount."""
    for row in rows:
        region, product, amount = row.split(",")
        yield {"region": region, "product": product, "amount": int(amount)}

def in_region(records, region):
    """Stage 3: keep only the records from one region."""
    for rec in records:
        if rec["region"] == region:
            yield rec

rows = read_rows(SALES)
records = parse(rows)
east = in_region(records, "East")
amounts = (rec["amount"] for rec in east)   # Stage 4: pick one field

print(type(amounts))   # <class 'generator'>  (nothing has run yet)
print(sum(amounts))    # 425  (sum() pulls every value through the chain)
<class 'generator'>
425

11.3.1.2. Tracing the Flow#

To see the order in which values move, insert a pass-through stage that prints each item and yields it unchanged. Because trace() is itself a generator, you can drop it between any two stages without changing the result.

def trace(label, items):
    """Pass items through unchanged, printing each one."""
    for item in items:
        print(f"{label:>5}: {item}")
        yield item

rows = trace("read", read_rows(SALES))
records = trace("parse", parse(rows))
east = trace("keep", in_region(records, "East"))

total = sum(rec["amount"] for rec in east)
print("total:", total)   # total: 425
 read: East,apple,120
parse: {'region': 'East', 'product': 'apple', 'amount': 120}
 keep: {'region': 'East', 'product': 'apple', 'amount': 120}
 read: West,banana,85
parse: {'region': 'West', 'product': 'banana', 'amount': 85}
 read: East,cherry,210
parse: {'region': 'East', 'product': 'cherry', 'amount': 210}
 keep: {'region': 'East', 'product': 'cherry', 'amount': 210}
 read: West,apple,40
parse: {'region': 'West', 'product': 'apple', 'amount': 40}
 read: East,banana,95
parse: {'region': 'East', 'product': 'banana', 'amount': 95}
 keep: {'region': 'East', 'product': 'banana', 'amount': 95}
total: 425

Read the trace from top to bottom. The first line is read, parsed, and kept before the second line is even read. The West records stop at the filter, so sum() never sees them. At any moment only one record is in flight, which is why the pipeline scales: if the first stage reads from a file (for line in f:) instead of an in-memory string, memory use depends on the size of one record, not the number of records.

11.3.1.3. Iterator Exhaustion#

A generator remembers its position, and it cannot rewind. Once it has raised StopIteration, it is exhausted: every later request ends immediately. This is called iterator exhaustion. It matters in pipelines because a second pass over the same generator silently produces nothing. sum() of an empty stream returns 0 and list() returns [], so no error warns you. max() and min() are the exception: they raise ValueError on an empty stream, which is often the first sign that a generator was already used.

east = in_region(parse(read_rows(SALES)), "East")
amounts = (rec["amount"] for rec in east)

print(sum(amounts))    # 425
print(sum(amounts))    # 0   (the generator is already exhausted)
print(list(amounts))   # []

try:
    max(amounts)
except ValueError as e:
    print("ValueError:", e)   # max() of an empty stream
425
0
[]
ValueError: max() iterable argument is empty

There are two fixes, and you choose based on how much data there is:

  • Rebuild the pipeline. Wrap the chain in a function that returns a fresh generator each time you call it. Each call reads the source again, but memory use stays constant.

  • Materialize once. Call list() on the pipeline when you need the same values several times and they fit in memory. A list can be iterated as often as you like.

def east_amounts(text):
    """Build a fresh pipeline every time it is called."""
    records = in_region(parse(read_rows(text)), "East")
    return (rec["amount"] for rec in records)

# Fix 1: rebuild the pipeline for each pass
print(sum(east_amounts(SALES)))   # 425
print(max(east_amounts(SALES)))   # 210

# Fix 2: materialize once, then reuse the list
amounts = list(east_amounts(SALES))
print(amounts)                                    # [120, 210, 95]
print(sum(amounts), max(amounts), len(amounts))   # 425 210 3
425
210
[120, 210, 95]
425 210 3
### Exercise: Generator Pipeline
#   1. Write a generator function `parse_scores(text)` that skips the header
#      and yields one (name, score) tuple per line, with score as an int.
#   2. Write a function `passing(text, cutoff)` that returns a generator
#      expression over parse_scores(text) keeping only scores >= cutoff.
#   3. With cutoff 75, print how many scores pass and the highest passing
#      score. Build a fresh pipeline for each result.
#   Print exactly:
#   4 95
SCORES = """name,quiz,score
Alice,1,88
Bob,1,72
Carol,1,95
Alice,2,91
Bob,2,58
Carol,2,79"""
### Your code starts here.




### Your code ends here.

Hide code cell source

### Solution
SCORES = """name,quiz,score
Alice,1,88
Bob,1,72
Carol,1,95
Alice,2,91
Bob,2,58
Carol,2,79"""

def parse_scores(text):
    lines = iter(text.splitlines())
    next(lines)                          # skip the header row
    for line in lines:
        name, quiz, score = line.split(",")
        yield name, int(score)

def passing(text, cutoff):
    return ((name, score) for name, score in parse_scores(text) if score >= cutoff)

count = sum(1 for _ in passing(SCORES, 75))
best = max(score for name, score in passing(SCORES, 75))
print(count, best)                 # 4 95
4 95

11.3.2. Infinite Sequences#

Generators also shine when a sequence is too large to build all at once, or has no end at all. The example below represents an endless sequence and takes only as many values as it needs.

Warning

Never pass an infinite generator to list(), sum(), max(), or a for loop without a break. These consumers keep asking for values that never run out, so the cell runs forever (and with list(), memory keeps growing too). Bound it first with itertools.islice() or stop at a condition with next(). If a cell does hang, use the notebook’s interrupt (stop) button.

import itertools

def fibonacci():
    """Infinite Fibonacci sequence generator."""
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

# Take only the values you need; the rest is never computed
fib = fibonacci()
first_10 = list(itertools.islice(fib, 10))
print("First 10 Fibonacci:", first_10)  # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

# Find the first Fibonacci number > 1000
fib = fibonacci()
big = next(f for f in fib if f > 1000)
print("First Fibonacci > 1000:", big)   # 1597
First 10 Fibonacci: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
First Fibonacci > 1000: 1597
### Exercise: Powers of Two
#   1. Write an infinite generator function `powers_of_two()` that yields
#      1, 2, 4, 8, ... forever.
#   2. Use itertools.islice to print the first 8 powers as a list.
#   3. Use next() with a generator expression over a fresh powers_of_two()
#      to print the first power greater than 1000.
#   Print exactly:
#   [1, 2, 4, 8, 16, 32, 64, 128]
#   1024
import itertools
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
import itertools

def powers_of_two():
    value = 1
    while True:
        yield value
        value *= 2

print(list(itertools.islice(powers_of_two(), 8)))   # [1, 2, 4, 8, 16, 32, 64, 128]
print(next(p for p in powers_of_two() if p > 1000))  # 1024
[1, 2, 4, 8, 16, 32, 64, 128]
1024

11.3.3. yield from#

yield from delegates yielding to another iterable (including another generator). For ordinary iteration, it is a shorthand for for item in sub: yield item.

def flatten(nested):
    """Recursively flatten a nested list structure."""
    for item in nested:
        if isinstance(item, list):
            yield from flatten(item)  # delegate to recursive call
        else:
            yield item

data = [1, [2, 3], [4, [5, 6]], 7]
print(list(flatten(data)))   # [1, 2, 3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7]
# yield from with multiple sub-generators
def combined(*iterables):
    for it in iterables:
        yield from it

result = list(combined([1, 2], 'ab', range(3)))
print(result)   # [1, 2, 'a', 'b', 0, 1, 2]
[1, 2, 'a', 'b', 0, 1, 2]
### Exercise: Shelf Inventory with yield from
#   1. Write a generator function `inventory(*shelves)` that uses `yield from`
#      to produce every item on each shelf in order, then yields "END"
#      after the last shelf.
#   2. Print list(inventory(...)) for the three shelves below.
#   Print exactly:
#   ['pen', 'ink', 'mug', 'END']
front = ['pen', 'ink']
back = ['mug']
empty = []
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
front = ['pen', 'ink']
back = ['mug']
empty = []

def inventory(*shelves):
    for shelf in shelves:
        yield from shelf   # an empty shelf yields nothing
    yield "END"

print(list(inventory(front, back, empty)))   # ['pen', 'ink', 'mug', 'END']
['pen', 'ink', 'mug', 'END']

11.3.4. More itertools#

The itertools module provides iterator building-blocks. Beyond islice, five more are especially useful in data processing.

Function

Description

Example

chain(*iterables)

Joins iterables end to end, lazily

chain('AB', 'CD') → A, B, C, D

count(start, step)

Infinite counter

count(1, 2) → 1, 3, 5, …

cycle(iterable)

Repeats iterable endlessly

cycle('AB') → A, B, A, B, …

combinations(it, r)

All r-length combos (order doesn’t matter)

combinations('ABC', 2) → AB AC BC

permutations(it, r)

All ordered r-length arrangements

permutations('AB', 2) → AB BA

import itertools

# count: infinite arithmetic sequence
evens = itertools.islice(itertools.count(0, 2), 5)
print('First 5 even numbers:', list(evens))  # [0, 2, 4, 6, 8]

# cycle: the library version of the Cycle class from Iterators
servers = ['A', 'B', 'C']
requests = list(itertools.islice(itertools.cycle(servers), 7))
print('Request routing:', requests)   # ['A', 'B', 'C', 'A', 'B', 'C', 'A']
First 5 even numbers: [0, 2, 4, 6, 8]
Request routing: ['A', 'B', 'C', 'A', 'B', 'C', 'A']

chain() connects several iterables into one stream. It reads the first iterable to the end and then moves on to the next one, without copying anything into a new list. You can think of it as the library version of the combined() generator from the yield from section. Because chain() is lazy, it works with generators as well as lists: nothing is read from any input until you ask for values.

chain.from_iterable() does the same job for a single iterable whose items are themselves iterables, such as a list of lists.

import itertools

morning = ['apple', 'banana']                                  # a list
afternoon = (fruit.upper() for fruit in ['cherry', 'date'])    # a generator

all_fruits = itertools.chain(morning, afternoon)
print(type(all_fruits).__name__)   # chain  (nothing has been read yet)
print(list(all_fruits))            # ['apple', 'banana', 'CHERRY', 'DATE']

# chain.from_iterable: flatten one level of a list of lists
baskets = [[1, 2], [3], [4, 5]]
print(list(itertools.chain.from_iterable(baskets)))   # [1, 2, 3, 4, 5]
chain
['apple', 'banana', 'CHERRY', 'DATE']
[1, 2, 3, 4, 5]
import itertools

# combinations: choose without caring about order
teams = list(itertools.combinations(['Alice', 'Bob', 'Carol'], 2))
print('Possible pairs:', teams)
# [('Alice', 'Bob'), ('Alice', 'Carol'), ('Bob', 'Carol')]

# permutations: order matters (e.g. race positions)
podium = list(itertools.permutations(['Gold', 'Silver', 'Bronze'], 2))
print(f'Top-2 orderings: {len(podium)} total')
print(podium[:3])   # first 3 arrangements
Possible pairs: [('Alice', 'Bob'), ('Alice', 'Carol'), ('Bob', 'Carol')]
Top-2 orderings: 6 total
[('Gold', 'Silver'), ('Gold', 'Bronze'), ('Silver', 'Gold')]
### Exercise: itertools
#   1. Use itertools.count() and islice() to generate the first 8
#      multiples of 7 (7, 14, 21, ..., 56).
#   2. Deal cards 1 to 12 to 4 players in turn. Use itertools.cycle() for the
#      players 'North', 'East', 'South', 'West', and zip() it with range(1, 13).
#      zip() stops at the shorter input, which bounds the infinite cycle.
#      Print the list of (player, card) pairs.
#   3. Use itertools.combinations() to find all 3-letter combinations
#      from 'ABCDE' and print how many there are.
#   Print exactly:
#   [7, 14, 21, 28, 35, 42, 49, 56]
#   [('North', 1), ('East', 2), ('South', 3), ('West', 4), ('North', 5), ('East', 6), ('South', 7), ('West', 8), ('North', 9), ('East', 10), ('South', 11), ('West', 12)]
#   10 combinations
import itertools

### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
import itertools

# 1. First 8 multiples of 7
multiples = list(itertools.islice(itertools.count(7, 7), 8))
print(multiples)   # [7, 14, 21, 28, 35, 42, 49, 56]

# 2. Deal 3 cards each to 4 players
players = itertools.cycle(['North', 'East', 'South', 'West'])
cards   = range(1, 13)  # card values 1-12
deal    = list(zip(players, cards))   # zip stops when cards runs out
print(deal)
# [('North', 1), ('East', 2), ('South', 3), ('West', 4),
#  ('North', 5), ('East', 6), ...]

# 3. Count 3-letter combinations from 'ABCDE'
combos = list(itertools.combinations('ABCDE', 3))
print(f'{len(combos)} combinations')   # 10
[7, 14, 21, 28, 35, 42, 49, 56]
[('North', 1), ('East', 2), ('South', 3), ('West', 4), ('North', 5), ('East', 6), ('South', 7), ('West', 8), ('North', 9), ('East', 10), ('South', 11), ('West', 12)]
10 combinations

11.3.5. Bridge: Async Iteration#

Synchronous generators pause at yield and resume when next() is called, all within a single thread. Async generators do the same thing, but they can also pause to wait for I/O (a network response, a database query, a file read) without blocking other work.

The pattern mirrors what you have seen, but uses async def with yield, and requires async for to consume:

import asyncio

async def async_count(n):
    """Yields 0..n-1, simulating a pause between each."""
    for i in range(n):
        await asyncio.sleep(0)   # hands control back to the event loop
        yield i

async def main():
    async for value in async_count(5):
        print(value)

asyncio.run(main())   # 0 1 2 3 4  (in a script)

In a Jupyter notebook an event loop is already running, so asyncio.run() raises RuntimeError. In a notebook cell, write await main() instead.

Key vocabulary for future study:

Term

Meaning

async def

Declares a coroutine (or async generator if it uses yield)

await

Pauses the coroutine until the awaited task is ready

async for

Iterates over an async iterable, awaiting each item; other tasks can run while it waits

Event loop

The scheduler that runs coroutines concurrently

You do not need to master asyncio now. The takeaway: async iteration mirrors the protocol you learned here. An async iterator implements __aiter__() and __anext__() instead of __iter__() and __next__(), signals the end with StopAsyncIteration, and an async generator pauses at yield the same way a generator does.

11.3.6. Choosing a Tool#

Each tool in this chapter fits a different job. Start with the simplest one that works:

You need

Use

Example

Values you will use several times, or need len() or indexing

a list

prices = [12, 5, 8]

One pass of a simple transform or filter

a generator expression

sum(p * 1.1 for p in prices)

One pass with several steps, state, or try/except

a generator function

running_total(numbers)

An object that can be looped over many times

a class whose __iter__() is a generator

CountdownRange(3)

An iterator with extra methods or state that other code inspects

a class with __iter__() and __next__()

Countdown(5) (protocol demo)

A standard pattern: slicing, joining, repeating, combining

itertools

islice, chain, cycle

11.3.7. Exercises#

This task combines generator functions, generator expressions, a pipeline, itertools.islice, and the fix for iterator exhaustion.

### Exercise: Error Log Pipeline
#   1. Write a generator function `parse_log(text)` that skips the header
#      and yields one (time, level, message) tuple per line.
#   2. Write a generator function `errors(records)` that yields only the
#      records whose level is "ERROR".
#   3. Write `error_stream(text)` that connects the two stages and returns
#      a fresh pipeline each time it is called.
#   4. Use itertools.islice to print the times of the first two errors.
#   5. Use any() with a generator expression to check whether any error
#      message is "timeout".
#   6. Use sum() with a generator expression to count the errors.
#   Build a fresh pipeline for steps 4, 5, and 6.
#   Print exactly:
#   First two errors: ['09:05', '09:10']
#   Any timeout: True
#   Error count: 3
LOG = """time,level,message
09:00,INFO,start
09:05,ERROR,disk full
09:07,INFO,retry
09:10,ERROR,timeout
09:12,WARN,slow
09:15,ERROR,disk full"""
import itertools
### Your code starts here.



### Your code ends here.

Hide code cell source

### Solution
import itertools

LOG = """time,level,message
09:00,INFO,start
09:05,ERROR,disk full
09:07,INFO,retry
09:10,ERROR,timeout
09:12,WARN,slow
09:15,ERROR,disk full"""

def parse_log(text):
    lines = iter(text.splitlines())
    next(lines)                          # skip the header row
    for line in lines:
        time, level, message = line.split(",")
        yield time, level, message

def errors(records):
    for time, level, message in records:
        if level == "ERROR":
            yield time, level, message

def error_stream(text):
    return errors(parse_log(text))

first_two = [time for time, _, _ in itertools.islice(error_stream(LOG), 2)]
print("First two errors:", first_two)
print("Any timeout:", any(msg == "timeout" for _, _, msg in error_stream(LOG)))
print("Error count:", sum(1 for _ in error_stream(LOG)))
First two errors: ['09:05', '09:10']
Any timeout: True
Error count: 3