Split into Chunks
Write chunk(items, size) that returns a list of lists, each with at most size items, in order. The last chunk may be shorter. chunk([1, 2, 3, 4, 5], 2) is [[1, 2], [3, 4], [5]].
If size is zero or negative, raise a ValueError.
Understand the problem
Look at the two tools you will combine.
What is list(range(0, 7, 3))? Type the list.
range(start, stop, step) counts in steps of 3: 0, 3, 6. These are exactly the starting positions of chunks of size 3 in a list of 7 items.
What is [1, 2, 3][2:10]? The slice goes past the end.
A slice never raises an error for positions beyond the end: it just stops at the end. So the last, short chunk is produced without any special code.
Write the solution
Return the chunks and raise ValueError for a size below 1.
def chunk(items, size):
# Write your code here.
pass
Hint 1: a question to ask yourself
Where does each chunk start, and where does it end?
Hint 2: the shape of the answer
Check size first. Then a list comprehension over range(0, len(items), size) taking items[i:i + size].
Reflect
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)]
Another way: a while loop
def chunk(items, size):
if size < 1:
raise ValueError("size must be at least 1")
result = []
position = 0
while position < len(items):
result.append(items[position:position + size])
position += size
return result
What this tests: range with a step, slicing past the end, a list comprehension, and validating input by raising an exception.
Why check the size yourself: range(0, n, 0) raises a ValueError on its own, but a negative step silently gives an empty range, so chunk([1, 2], -1) would return [] instead of complaining. Explicit validation gives a clear message and catches both.
Cost: O(n) time and space.
What an interviewer might ask next: Make it work for any iterable, including a generator that cannot be sliced. (Use itertools.islice in a loop; this is the generator version in a later chapter.)
VISIBLE = 3
CASES = [
(([1, 2, 3, 4, 5], 2), [[1, 2], [3, 4], [5]], 'a short last chunk'),
(([1, 2, 3, 4], 2), [[1, 2], [3, 4]], 'an exact fit'),
(([], 3), [], 'an empty list'),
(([1, 2], 5), [[1, 2]], 'size larger than the list'),
(([1, 2, 3], 1), [[1], [2], [3]], 'chunks of one'),
(('abcdefg', 3), ['abc', 'def', 'g'], 'it works on strings too'),
('result = error_of(chunk, [1, 2], 0)', 'ValueError', 'size zero is an error'),
('result = error_of(chunk, [1, 2], -1)', 'ValueError', 'a negative size is an error'),
]