Chunk an iterable into fixed-size batches

Python

itertools.batched on 3.12 and later; the islice version works everywhere and never materialises the whole input.

from itertools import batched, islice

for chunk in batched(rows, 500):
    insert_many(chunk)

# Before 3.12:
def chunks(it, size):
    it = iter(it)
    while batch := list(islice(it, size)):
        yield batch

More in Python

Random picks