Combine and Batch Iterables
Core idea
Use chain(*iterables) to traverse sources consecutively, or chain.from_iterable(sources) when the sources themselves arrive as an iterable. batched(iterable, n) yields tuples containing at most n items, with n at least one. It appeared in Python 3.12; strict=True requires Python 3.13 or later.
from itertools import chainprint(list(chain([12, 14], [], [19])))Empty sources contribute no items. The source order is preserved.
Batch a combined stream
from itertools import chain, batchedrows = [[11], [12, 13], [14, 15]]print(list(batched(chain.from_iterable(rows), 2)))Batch boundaries need not match source boundaries. The last tuple can be short.
Intentional incomplete batch error
from itertools import batchedlist(batched([11, 12, 13], 2, strict=True))Strict mode raises when the incomplete final batch is consumed, not when the iterator is created.
Common mistake
Strict batching does not roll back previously yielded batches. Validate before committing if the whole operation must be atomic.
Practice
Combine two lists of shipment IDs and divide into groups of three; try a total of four IDs and predict the final tuple.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Combine and batch streams
Check your understanding of chain and batching.
What is printed?
from itertools import chainprint(list(chain.from_iterable([[4], [], [1, 2]])))What is printed?
from itertools import batchedprint(list(batched([4, 8, 9], 2)))What happens?
from itertools import batchedlist(batched([1], 2, strict=True))Which Python version introduced the strict option for batched?