Split records into batches
Task
APIs and bulk loaders often take at most N records per call. Write chunk(items, size) that returns a list of lists of at most size items, in order, keeping the final partial batch. If size is less than 1, raise ValueError.
Python 3.14 running in your browser (Pyodide). Standard library only. print() output is shown below the results.
Tests
| Call | Expected |
|---|---|
chunk([1, 2, 3, 4, 5], 2) | [[1, 2], [3, 4], [5]] |
chunk([], 3) | [] |
chunk([1, 2], 5) | [[1, 2]] |
chunk(['a', 'b', 'c'], 1) | [['a'], ['b'], ['c']] |
chunk([1, 2, 3], 0) | raises ValueError |
chunk([1, 2, 3], -1) | raises ValueError |
range(0, len(items), size)gives the start index of every batch.- Check the size before slicing; a negative step would make
rangesilently return nothing.
Show solution
def chunk(items, size):
if size < 1:
raise ValueError('size must be at least 1')
return [items[i:i + size] for i in range(0, len(items), size)]Slicing never fails past the end of a list, so the last partial batch comes for free. In Python 3.12+ itertools.batched(items, size) does the same lazily, yielding tuples.
Why this works
Slicing never fails past the end of a list, so the last partial batch comes for free. In Python 3.12+ itertools.batched(items, size) does the same lazily, yielding tuples.
Revise in the Python for Data Engineers guide, or test yourself with the Python practice sets.