Break a list into fixed-size pieces
A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.
- Every piece is the given size except possibly the last, which takes what is left.
- A size of zero or less gives an empty result.
- An empty input gives an empty result, not a list holding one empty piece.
chunk_list(values: list<int>, per_chunk: int) → list<list<int>>
Where you start
def chunk_list(values: list[int], per_chunk: int) -> list[list[int]]:
Worked examples
| Call | Result |
|---|---|
chunk_list([1, 2, 3, 4, 5], 2) | [[1, 2], [3, 4], [5]] |
chunk_list([1, 2, 3, 4], 2) | [[1, 2], [3, 4]] |
chunk_list([1], 5) | [[1]] |
chunk_list([], 2) | [] |
Hint
Step the index forward by the chunk size and slice, rather than pushing one item at a time.
Reference solution in Python
def chunk_list(values: list[int], per_chunk: int) -> list[list[int]]:
if per_chunk <= 0:
return []
return [values[i:i + per_chunk] for i in range(0, len(values), per_chunk)]