easy +10 pts

Chunk list into groups

Split a list into fixed-size chunks, preserving order and handling uneven tails.

Write a function `chunk_list(items, chunk_size)` that takes a list `items` and a positive integer `chunk_size`. It should return a list of sublists, each containing up to `chunk_size` elements from the original list in order. The last sublist may be shorter if the total length is not an exact multiple of `chunk_size`. **Example:** `chunk_list([1,2,3,4,5], 2)` returns `[[1,2],[3,4],[5]]`. The function should handle an empty input list (returning an empty list) and a `chunk_size` larger than the list length (returning a single sublist containing all elements).

Constraints

`items` is a list. `chunk_size` is an integer ≥ 1. Do not modify the input list. Time complexity O(n), where n is the length of items.

Example

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

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a for loop with `range(0, len(items), chunk_size)`.
Slice `items[i:i + chunk_size]` to get each chunk.
Append each slice to a result list and return it.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.