Yield Records in Batches

Medium ⏱ 12 min 47% acceptance ★★★★☆ 4.4
Write the generator batched(iterable, size) yielding lists of up to size items — accumulating a buffer, yielding when full, and yielding the final partial batch if any. Works on any iterable, including other generators, without materializing the whole input.

Examples

Example 1
Input
list(batched(range(5), 2))
Output
[[0, 1], [2, 3], [4]]
Explanation

Two full batches and a remainder.

Constraints

  • Never build the full input list.
  • Final partial batch included.

Topics

Iterators & Generatorsbatching

Companies

AmazonDatabricksSnowflake

Hints

Hint 1

Append to a buffer; yield and reset at size.

Hint 2

After the loop, yield the leftovers if non-empty.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.