Sub topic 5
Joining sequences with chain and chain.from_iterable
This chapter assumes you know how iterators work and why they are used once (see the earlier chapters on the iteration protocol and lazy evaluation). You should also be comfortable with generator expressions and * argument unpacking.
The problem: joining without copying
Suppose you want to loop over several collections as if they were one. The obvious tool is +:
first = [1, 2]
second = [3, 4]
for x in first + second:
print(x)This builds a new list holding every element. It also fails when the inputs have different types, such as a list and a tuple, and it cannot be used on generators. itertools.chain avoids all three problems.
chain: several iterables in a row
chain(*iterables) returns an iterator. It yields everything from the first iterable, then everything from the second, and so on. It copies nothing, and the inputs can be any mix of iterable types.
from itertools import chain
a = [1, 2]
b = (3, 4)
c = range(5, 7)
print(list(chain(a, b, c)))This prints [1, 2, 3, 4, 5, 6]. Each input is only asked for its next item when the consumer needs it.
chain.from_iterable: an iterable of iterables
When the inputs are already collected in one iterable, such as a list of rows, you could write chain(*rows). That works, but * unpacks the whole outer iterable into arguments before chain starts. If the outer iterable is a generator, every inner item must be produced first. If it is infinite, the call never returns.
chain.from_iterable(iterable) is an alternative constructor that takes the outer iterable as one argument and pulls inner iterables only when needed.
from itertools import chain
def rows():
for i in range(3):
print("producing row", i)
yield [i, i + 10]
flat = chain.from_iterable(rows())
print(next(flat))
print(next(flat))
print(next(flat))The output shows that rows are produced on demand:
producing row 0
0
10
producing row 1
1With chain(*rows()), all three "producing row" lines would print before the first value came out.
A common use is flattening one level of nesting:
from itertools import chain
rows = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(rows)))This prints [1, 2, 3, 4, 5].
Choosing between them
| Situation | Use |
|---|---|
| A few iterables known when you write the code | `chain(a, b, c)` |
| A list, generator or stream of iterables | `chain.from_iterable(outer)` |
| Outer iterable may be large or infinite | `chain.from_iterable(outer)` |
Common errors
chain flattens exactly one level. Deeper nesting is left alone, and strings count as iterables of characters:
from itertools import chain
print(list(chain.from_iterable([[1, [2, 3]], [4]])))
print(list(chain.from_iterable(['ab', 'cd'])))This prints [1, [2, 3], 4] and then ['a', 'b', 'c', 'd']. If you pass a list of strings and expect the strings to stay whole, use chain(['ab', 'cd']) or just the list itself.
Two more points:
- The result is an iterator, so it is exhausted after one pass. Wrap it in
list(...)only if you need to reuse it. - Passing a non-iterable, such as
chain(1, [2]), raisesTypeErrorwhenchainreaches that item, not when you create the chain.
Exercise
Given lines = ["a b", "c d e"], write an expression using chain.from_iterable that lazily yields every word from every line, and state what list() of it returns.
Show answer
chain.from_iterable(line.split() for line in lines). The list is ['a', 'b', 'c', 'd', 'e'].
Exercise
Why is chain.from_iterable(gen()) preferred over chain(*gen()) when gen() produces a very large number of inner iterables?
Show answer
The * operator unpacks the entire outer iterable into arguments before chain starts, so every inner iterable is created up front (and an infinite outer iterable never finishes). from_iterable takes inner iterables one at a time, only when the consumer asks for more values.