Add itertools.batched()

rhettinger · GitHub

This was requested on python-ideas:

def batched(iterable, n): "Batch data into lists of length n. The last batch may be shorter." # batched('ABCDEFG', 3) --> ABC DEF G if n < 1: raise ValueError('n must be >= 1') it = iter(iterable) while (batch := list(islice(it, n))): yield batch Linked PRs

GH-98363: Have batched() return tuples #100118

GH-98363: Shrink the physical size as well as the logical size #100138

[3.11] GH-98363: Update batched() recipe in docs to match 3.12 #100323