Lazy Batching Generator

easy
Checkpoint challenge
Solve this to show you know the material and jump straight to Unit 8. Everything before it counts as cleared.

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