Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.batched

Consumes an iterable in consecutive tuples of at most the requested size.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.batched(iterable, n, *, strict=False)

Consumes an iterable in consecutive tuples of at most the requested size.

The default keeps a short final batch. Strict mode raises ValueError if the last batch is incomplete.

Batch size n must be at least one. Reading abcde in twos produces two pairs followed by a shorter singleton tuple containing e. The function was added in 3.12 and the strict option in 3.13. Empty input yields no batch. With strict=True, encountering an incomplete final batch raises ValueError during iteration, after any earlier complete batches.

import itertools as I
chunks = I.batched("abc", 2, strict=True)
assert next(chunks) == ("a", "b")
try:
    next(chunks)
except ValueError:
    pass
else:
    raise AssertionError

Examples

import itertools as I
print(list(I.batched("abcde", 2)))
print(list(I.batched([], 3)))

Result

[('a', 'b'), ('c', 'd'), ('e',)]
[]

Batch size n must be at least one. Reading abcde in twos produces two pairs followed by a shorter singleton tuple containing e. The function was added in 3.12 and the strict option in 3.13. Empty input yields no batch. With strict=True, encountering an incomplete final batch raises ValueError during iteration, after any earlier complete batches.

Sources