Lazy Batching Generator

easy
Unit 7 · Datetime I0/3 to milestone

Embedding APIs and databases work best in batches, say 100 texts per request. Write a generator that groups any iterable into batches lazily, so it works on huge files and even infinite streams.

Implement batched(iterable, n):

  • Yield tuples of n items. The last tuple may be shorter. Never yield an empty tuple.
  • It must be lazy: pull items from iterable only as needed. Don't call list() on the input.
  • Raise ValueError if n < 1.
  • Don't use itertools.batched. Write it yourself.

Example

list(batched("abcdefg", 3))   # [('a', 'b', 'c'), ('d', 'e', 'f'), ('g',)]
#generators#iterators3 visible + 3 hidden tests
solution.py · Python 3.13
Loading editor…
Run your code to see results. ⌘↵ to run · ⌘⇧↵ to submit
Lazy Batching Generator · TechGradify