more_itertools

s3manifesto.more_itertools.batched(iterable: Iterable[T_ITEM], n: int, *, strict: bool = False) Iterator[list[T_ITEM]][source]

Batch data into lists of length n. If the number of items in iterable is not divisible by n:

  • The last batch will be shorter if strict is False.

  • ValueError will be raised if strict is True.

>>> list(batched('ABCDEFG', 3))
[['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]
Args:

iterable: An iterable of items of type T n: Batch size (must be at least 1) strict: If True, raises ValueError if the last batch is incomplete

Returns:

Iterator yielding lists of items from the input iterable

Raises:

ValueError: If n < 1 or if strict=True and last batch is incomplete