10.11. Iterator Batched

  • Lazy evaluated

  • Batch data from the iterable into tuples of length n. The last batch may be shorter than n.

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

Loops over the input iterable and accumulates data into tuples up to size n. The input is consumed lazily, just enough to fill a batch. The result is yielded as soon as the batch is full or when the input iterable is exhausted:

>>> from itertools import batched
>>>
>>>
>>> data = ['alice', 'bob', 'carol', 'dave', 'eve', 'mallory']
>>> result = batched(data, 2)
>>>
>>> print(list(result))
[('alice', 'bob'), ('carol', 'dave'), ('eve', 'mallory')]