brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: itertools.batched splits a list into chunks of n

Python
~/tips/tip-python-itertools-batched

from itertools import batched

Splits any iterable into tuples of a fixed size, with the standard library only.

Sending 1,000 records to an API that takes 100 at a time is a classic. Everyone has written the same slicing loop for it, or copied a recipe. Since Python 3.12 it’s in the standard library.

from itertools import batched

for chunk in batched(range(7), 3):
    print(chunk)
# (0, 1, 2)
# (3, 4, 5)
# (6,)

The docs describe it as batching data into tuples of length n, where the last batch may be shorter. It works on any iterable, generators and files included, so you don’t have to load everything into a list first.

A real example, deleting files through an API in batches of 100:

for ids in batched(file_ids, 100):
    api.delete_many(list(ids))

Note the list(ids): you get tuples back, and some clients want a list.

Python 3.13 added strict=True. Then a short last batch raises a ValueError instead of passing quietly, which is what you want when the data must divide evenly, like pairs of keys and values.

Caveat: on 3.11 or older the import simply fails. Check python3 --version on the server where the script will run, not only on your laptop.

Further reading: Python docs: itertools.batched

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link