Batu Lab NotesPractical developer guides

Flatten one level of nested results with chain.from_iterable

By Batu ยท English technical notes

Also published in our Blogger archive.

Flatten one level of nested results with chain.from_iterable

By Batu.

chain.from_iterable(result_sets) accepts one outer iterable and visits each of its inner iterables in turn. In this example, result_sets has three outer elements: its first list holds two response tuples, its second list is empty, and its third list holds one response tuple. Converting the resulting chain to list produces those three response tuples in that order, skipping no data except the naturally empty inner list.

The method performs one level of concatenation. It does not recursively unpack each response tuple: ("alpha", 201) remains one record in flat. That property is useful when a nested shape represents batches while each inner object is a complete item. The assertion checks both the retained tuple structure and the ordering of the flattened result.

chain.from_iterable() itself is lazy, so it can start yielding from the first inner iterable without constructing a combined list. The list() call in this small fixture intentionally consumes it to show a concrete value. Every outer element must still be iterable; None causes TypeError. It is also easy to flatten the wrong level: if the inner elements are strings, their individual characters will be yielded. For arbitrary nesting depth, choose an explicit recursive or stack-based policy instead of assuming this function descends further.

Read the Python chain.from_iterable() documentation for the equivalent iteration pattern.

Batu used AI assistance while drafting this explanation.

from itertools import chain

result_sets = [
    [("alpha", 201), ("beta", 202)],
    [],
    [("gamma", 204)],
]

flat = list(chain.from_iterable(result_sets))
assert flat == [("alpha", 201), ("beta", 202), ("gamma", 204)]
assert all(isinstance(item, tuple) for item in flat)
print(flat)

Expected stdout:

[('alpha', 201), ('beta', 202), ('gamma', 204)]