Drill

ProblemsPython › warmup

Break a list into fixed-size pieces

mediumwarmupPython

A bulk API takes at most a hundred records per call, so a long list has to be handed over in pieces.

chunk_list(values: list<int>, per_chunk: int) → list<list<int>>

Solve it in the editor →

Where you start

def chunk_list(values: list[int], per_chunk: int) -> list[list[int]]:
    

Worked examples

CallResult
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)]

The same problem in another language

More warmup problems in Python