Split a list into evenly sized batches in Python

Splitting a list into evenly sized chunks or batches can be accomplished using Python.

Using `itertools.batched`

In Python 3.12, `itertools.batched` is available for consumption.

 ``````1 2 3 4 `````` ``````import itertools lst = ['mary', 'sam', 'joseph'] print(list(itertools.batched(lst, 2))) # [('mary', 'sam'), ('joseph')] ``````

Using `yield`

If the version of Python is lower than 3.12, the `yield` keyword may be used.

 ``````1 2 3 4 5 6 `````` ``````def chunks(lst, n): for i in range(0, len(lst), n): yield lst[i:i + n] lst = ['mary', 'sam', 'joseph'] print(list(chunks(lst, 2))) # [['mary', 'sam'], ['joseph']] ``````

Using `itertools.islice`

The `itertools.islice` function can additionally be used.

 ``````1 2 3 4 5 6 7 8 `````` ``````from itertools import islice def chunks(lst, n): it = iter(lst) return iter(lambda: tuple(islice(it, n)), ()) lst = ['mary', 'sam', 'joseph'] print(list(chunks(lst, 2))) # [('mary', 'sam'), ('joseph',)] ``````