easy +10 pts

Chunk a list into n-sized parts

Split any list into consecutive chunks of a fixed size.

Write a function `chunk_list(items, n)` that takes a list `items` and a positive integer `n`, and returns a new list of sublists, each containing up to `n` elements, preserving the original order. The last chunk may have fewer than `n` elements. If `items` is empty, return an empty list. If `n` is not positive, raise a `ValueError`.

Constraints

0 <= len(items) <= 100000 n >= 1 (must raise ValueError if n < 1) The chunks must be in order.

Example

>>> chunk_list([1,2,3,4,5], 2)
[[1,2], [3,4], [5]]
>>> chunk_list(['a','b','c'], 3)
[['a','b','c']]
>>> chunk_list([], 5)
[]
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a loop with range(start, len(items), n).
Slicing items[i:i+n] gives the next chunk.
Check n < 1 at the beginning and raise ValueError('n must be positive').
The result should be a list of lists, not a list of tuples.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.