Sub topic 5
Joining sequences with chain and chain.from_iterable
This chapter assumes you know Python loops and comprehensions, the difference between an iterable and an iterator (covered earlier in this tutorial), and what a generator is. By the end you will be able to join any number of iterables into one stream. You will also know when to choose chain.from_iterable over chain, and which mistakes to avoid.
The problem: joining things that are not the same type
Suppose you want to loop over a list, a tuple and a string as one sequence. The + operator does not help:
print([1, 2] + (3,))This raises TypeError: can only concatenate list (not "tuple") to list. Even when the types match, + builds a new list that holds every element, so it costs time and memory proportional to the total size. Joining a generator with + is not possible at all.
itertools.chain solves both problems. It takes any number of iterables and returns one iterator that yields the items of the first, then the second, and so on. It copies nothing.
chain: the basics
from itertools import chain
joined = chain([1, 2], (3,), "ab", range(4, 6))
print(list(joined))This prints [1, 2, 3, 'a', 'b', 4, 5]. The inputs have four different types. chain only requires that each argument can be passed to iter().
The result is an iterator, not a list. It has no length, it cannot be indexed, and it can be consumed only once:
from itertools import chain
stream = chain("ab", "cd")
print(list(stream))
print(list(stream))The first call prints ['a', 'b', 'c', 'd'] and the second prints [].
chain is lazy about its inputs too
chain does not call iter() on an argument until it reaches it. A generator passed to chain does not run any of its code until the earlier inputs are exhausted:
from itertools import chain
def noisy(name, items):
print(f"start {name}")
yield from items
stream = chain(noisy("a", [1, 2]), noisy("b", [3]))
print("created")
print(next(stream))
print(next(stream))
print(next(stream))The output is, in order: created, start a, 1, 2, start b, 3.
This has an observable side effect. If an input is a mutable list, chain sees changes made to it before iteration reaches it:
from itertools import chain
a = [1]
b = [2]
stream = chain(a, b)
b.append(3)
print(list(stream))This prints [1, 2, 3]. The list b was not iterated until a was finished, so the appended 3 is included. If you need a snapshot, copy the list yourself.
Also note that an argument which is not iterable fails late. chain(5) is created without an error, and the TypeError appears only when iteration reaches that argument.
Common uses of chain
Prepending a header row or appending a sentinel value to a stream, without building a new list:
from itertools import chain
rows = [("alice", 3), ("bob", 5)]
for row in chain([("name", "count")], rows):
print(row)Looping over several collections with one for statement:
from itertools import chain
admins = {"root", "ops"}
guests = ["tmp1", "tmp2"]
for user in chain(admins, guests):
print(user.upper())Both examples use memory for one item at a time, however large the inputs are.
chain.from_iterable: when the inputs come as one iterable
chain(a, b, c) needs each input as a separate argument. If your inputs are already collected in one iterable, such as a list of rows, chain.from_iterable accepts that iterable and flattens it by one level:
from itertools import chain
rows = [[1, 2], [3], [4, 5]]
print(list(chain.from_iterable(rows)))This prints [1, 2, 3, 4, 5].
You could write chain(*rows) for the same result on a list. The two forms are not equivalent in general. The * operator unpacks the whole outer iterable into an argument tuple before chain starts, so the outer iterable is consumed completely and eagerly. from_iterable pulls inner iterables one at a time, only when needed.
from itertools import chain
def sources():
for n in range(3):
print("producing", n)
yield range(n, n + 2)
lazy = chain.from_iterable(sources())
print(next(lazy))
eager = chain(*sources())
print(next(eager))The first next prints producing 0 and then 0. The second prints producing 0, producing 1 and producing 2 before it prints 0. With a generator that reads files or calls a network service, the eager version does all that work up front.
The difference is more than a matter of timing. An infinite outer iterable works with from_iterable and hangs with *:
from itertools import chain, count, islice
nested = (range(n) for n in count(1))
print(list(islice(chain.from_iterable(nested), 8)))This prints [0, 0, 1, 0, 1, 2, 0, 1]. The outer generator never ends, but islice stops after eight items, so only the first four range objects are ever created. Writing chain(*nested) here would never finish, because the * operator would try to read the endless generator to its end.
A flat-map pattern
Combining map with from_iterable gives you a "flat map": apply a function that returns an iterable to every item, then join the results.
from itertools import chain
lines = ["a b", "c d e"]
print(list(chain.from_iterable(map(str.split, lines))))This prints ['a', 'b', 'c', 'd', 'e']. The equivalent comprehension is [w for line in lines for w in line.split()]. Use whichever reads better. The chain version stays lazy if you drop the list(...) call, while the comprehension builds a list immediately (a generator expression is the lazy form).
Comparing the options
| Approach | Accepts mixed types | Lazy | Copies data | Notes |
|---|---|---|---|---|
| `a + b` | No, same type only | No | Yes | Fine for two small lists |
| `sum(lists, [])` | No | No | Yes, repeatedly | Quadratic time, avoid |
| `chain(a, b, c)` | Yes | Yes | No | Fixed, known number of inputs |
| `chain(*xs)` | Yes | Inner only | No | Consumes `xs` fully first |
| `chain.from_iterable(xs)` | Yes | Yes, including `xs` | No | Best when inputs come as one iterable |
| Nested comprehension | Yes | No (lists) | Yes | Most flexible, builds a list |
Edge cases and gotchas
Only one level is flattened. chain.from_iterable([[1, [2]], [3]]) yields 1, [2] and 3. The inner list [2] is an item, not something to join. For arbitrary depth you need a recursive generator, which is outside itertools.
Strings are iterables. If one of your inputs is a string, chain yields its characters:
from itertools import chain
print(list(chain.from_iterable(["ab", "cd"])))
print(list(chain(["ab"], ["cd"])))The first line prints ['a', 'b', 'c', 'd'] and the second prints ['ab', 'cd']. If you meant to join the words as items, pass lists of words, not the words themselves.
Inputs that are iterators are consumed. If you pass an iterator to chain, the chain advances it. After the chain runs, that iterator is exhausted, and anything else sharing it sees the same state.
Empty cases are fine. chain() yields nothing, and empty inputs are skipped without error.
The result is a single pass. To iterate twice, either rebuild the chain from reusable inputs, or store the items with list() if they fit in memory.
Exercises
Exercise
What does list(chain.from_iterable(["ab", "cd"])) return, and why does it not return ['ab', 'cd']?
Show answer
It returns ['a', 'b', 'c', 'd']. from_iterable treats each item of the outer list as an iterable to join. Each string is an iterable of characters, so the characters are yielded one by one. To get ['ab', 'cd'], iterate the outer list directly or pass lists such as [["ab"], ["cd"]].
Exercise
A generator read_chunks() yields one list of records per file, and there are thousands of files. Which is better for processing every record, chain(*read_chunks()) or chain.from_iterable(read_chunks())? Explain the difference in behavior.
Show answer
chain.from_iterable(read_chunks()) is better. It asks the generator for the next file's records only when the previous ones are used up, so memory holds one chunk at a time and processing can start immediately. chain(*read_chunks()) first runs the generator to the end and holds all chunks as arguments, so it reads every file before yielding the first record and keeps all of them in memory.