Python Glossary Русский

Python 3.12+itertoolsfunction

itertools.batched

itertools

Batch an iterable into tuples of length n (the last may be shorter); 3.12+.

Syntax

itertools.batched(iterable, n)

It returns a lazy iterator of tuples, not a list, so wrap it in list() when you need everything at once. The old pre-3.12 chunking idiom zip(*[iter(it)]*n) silently dropped an incomplete final batch, whereas batched keeps it; since 3.13 strict=True demands equal-sized batches (else ValueError), and n below 1 always raises.

Examples

import itertools
print(list(itertools.batched([1, 2, 3, 4, 5], 2)))   # → [(1, 2), (3, 4), (5,)]
print(list(itertools.batched('abcdef', 3)))   # → [('a', 'b', 'c'), ('d', 'e', 'f')]
print([sum(b) for b in itertools.batched(range(1, 7), 3)])   # → [6, 15]
print(list(itertools.batched([], 3)))   # → []
print(list(itertools.batched([1, 2, 3], 0)))   # → ValueError

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy