Batu Lab NotesPractical developer guides

Flatten nested batches while preserving order

By Batu ยท English technical notes

Also published in our Blogger archive.

A batch-oriented interface often yields a sequence of smaller sequences. To make one continuous sequence without changing encounter order, pass the outer iterable to itertools.chain.from_iterable. In this example, the batches contain "a", "b", an empty batch, "c", "d", and "e"; the flattened list is ['a', 'b', 'c', 'd', 'e']. The empty inner list contributes no item.

itertools.chain.from_iterable visits each inner iterable in outer order, then yields its members in inner order. Calling list() materializes the result for a clear assertion and stable demonstration output. chain.from_iterable is a long-standing Python standard-library API, so this example has no newer API version requirement.

This is a one-level flattening operation. If an inner item itself is a list, it remains an item unless another flattening step is deliberately applied. It also assumes every batch is iterable: None or a scalar integer would raise TypeError. Strings deserve particular care, because they are iterable and would be expanded into characters rather than treated as indivisible labels. The assertion confirms the traversal order for the fixture only; it does not validate batch types or impose any business meaning on their contents.

AI assistance disclosure: this article was drafted with AI assistance and checked against the cited Python documentation.

from itertools import chain

batches = [["a", "b"], [], ["c"], ["d", "e"]]

flat = list(chain.from_iterable(batches))

assert flat == ["a", "b", "c", "d", "e"]
print(flat)
['a', 'b', 'c', 'd', 'e']