5. Use itertools.batched for chunking

Use itertools.batched() to split an iterable into fixed-size chunks instead of writing the indexing logic yourself.

Using the standard tool makes the chunking rule obvious immediately and avoids off-by-one mistakes in hand-written slice loops. It also keeps the code focused on what a batch means instead of on index arithmetic.

Note

Python 3.12+

5.1. Don’t do this

1items = list(range(10))
2batches = []
3for i in range(0, len(items), 3):
4    batches.append(items[i:i + 3])

5.2. Do this

1from itertools import batched
2
3items = list(range(10))
4batches = list(batched(items, 3))