On this page
itertools.batched
Prev: itertools.accumulate | Up: itertools | Next: itertools.chain
Rel: itertools.accumulate, itertools.chain, itertools.combinations, itertools.combinations_with_replacement
Ref: docs.python.org — itertools.batched
Tags: #public #python3 #stdlib #itertools
Import
import itertools
from itertools import batched
Signature & Overview
itertools.batched(iterable, n, *, strict=False)
Batch data into tuples of length n. The last batch may be shorter than n.
Usage
from itertools import batched
chunks = list(batched(range(7), 3))
assert chunks == [(0, 1, 2), (3, 4, 5), (6,)]
Gotchas
- Last batch may be shorter: Pass
strict=True(Python 3.13+) to raiseValueErrorif the final tuple has fewer thannelements. - Requires Python 3.12+: Yields tuples, and raises
ValueErrorifn < 1.
REPL Inspect
from itertools import batched
help(batched)
Linked from
- tuts/python3/stdlib_module/itertools
- tuts/python3/stdlib_module/itertools/accumulate
- tuts/python3/stdlib_module/itertools/chain
- tuts/python3/stdlib_module/itertools/combinations
- tuts/python3/stdlib_module/itertools/combinations_with_replacement
- tuts/python3/stdlib_module/itertools/compress
- tuts/python3/stdlib_module/itertools/count
- tuts/python3/stdlib_module/itertools/cycle
- tuts/python3/stdlib_module/itertools/dropwhile
- tuts/python3/stdlib_module/itertools/filterfalse
- tuts/python3/stdlib_module/itertools/groupby
- tuts/python3/stdlib_module/itertools/islice
- tuts/python3/stdlib_module/itertools/pairwise
- tuts/python3/stdlib_module/itertools/permutations
- tuts/python3/stdlib_module/itertools/product
- tuts/python3/stdlib_module/itertools/repeat
- tuts/python3/stdlib_module/itertools/starmap
- tuts/python3/stdlib_module/itertools/takewhile
- tuts/python3/stdlib_module/itertools/tee
- tuts/python3/stdlib_module/itertools/zip_longest
Related notes
- tuts/python3/stdlib_module/itertools/accumulate Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/chain Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/combinations_with_replacement Linked here; links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools Linked here; links to this page; shared tags: #stdlib
- tuts/python3/stdlib_module/itertools/compress links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/count links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/cycle links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/dropwhile links to this page; shared tags: #itertools, #stdlib
- tuts/python3/stdlib_module/itertools/filterfalse links to this page; shared tags: #itertools, #stdlib