10.12. 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 = [
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30},
... {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32},
... {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33},
... {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34},
... {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15},
... ]
>>>
>>> result = batched(DATA, n=2)
>>>
>>> next(result)
({'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30}, {'firstname': 'Bob', 'lastname': 'Blackthorn', 'age': 31})
>>>
>>> next(result)
({'firstname': 'Carol', 'lastname': 'Corn', 'age': 32}, {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33})
>>>
>>> next(result)
({'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34}, {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15})
>>>
>>> next(result)
Traceback (most recent call last):
StopIteration
10.12.1. Use Case - 1
>>> from itertools import batched
>>>
>>>
>>> data = ['alice', 'bob', 'carol', 'dave', 'eve', 'mallory']
>>> result = batched(data, n=2)
>>>
>>> print(list(result))
[('alice', 'bob'), ('carol', 'dave'), ('eve', 'mallory')]