Batch a stream lazily

easyPipelines~15 min · 8 tests

Embedding APIs take inputs in batches. Bulk loaders write rows in batches. The input is often too big to hold in memory, or never ends at all. So batching has to be lazy.

Write a generator batched(iterable, n):

  • Yield lists of n consecutive items from iterable.
  • The last list can be shorter. Never yield an empty list.
  • Be lazy: pull only as many items as the next batch needs. It must work on an infinite iterator.
  • If n < 1, raise ValueError.

Don’t use itertools.batched. Build it yourself.

>>> list(batched("abcdefg", 3))
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g']]
>>> from itertools import count, islice
>>> list(islice(batched(count(), 2), 3))
[[0, 1], [2, 3], [4, 5]]
Learn the ideaRead the lesson →
solution.pyPython 3.14 · Pyodide

Press ⌘ ↵ or Run to check the visible tests. Submit runs the hidden ones too. Everything runs in your browser.

⌘ ↵ to run