how.wtf

Split a list into evenly sized batches in Python

· Thomas Taylor

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.

1import itertools
2
3lst = ['mary', 'sam', 'joseph']
4print(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.

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

Using itertools.islice

The itertools.islice function can additionally be used.

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

#Python  

Reply to this post by email ↪