Back to Practice
#0071

Yield Fixed-Size Batches

MediumPython20 min15 XP

Problem

Given a list of items and a positive batch size, yield lists of at most that size until all items are consumed.

Why This Matters

Generators are useful for datasets, logs, API pages, and training loops where loading everything at once is wasteful.

Function Signature

def batches(items, size):

Examples

Example 1
Inputlist(batches([1,2,3,4,5], 2))
Output[[1,2], [3,4], [5]]

The final batch can be smaller than the requested size.

Constraints

  • Raise ValueError for size <= 0.
  • Yield lists.
  • Do not drop leftover items.
CodePython
Visible browser tests run here when available.
Testcases1 visible / 3 hidden categories
Uneven final batch
Input[1,2,3,4,5], 2
Expected[[1,2],[3,4],[5]]

The leftover item should still be yielded.

Hidden Test Categories
size larger than listempty listinvalid size