Splitting a list into chunks means cutting it into smaller lists of the same size. The last chunk is shorter when the items do not divide evenly.
The program
python
def chunk(items, size): if size < 1: raise ValueError("size must be at least 1") chunks = [] for start in range(0, len(items), size): chunks.append(items[start:start + size]) return chunks players = ["Ada", "Linus", "Grace", "Alan", "Hedy", "Margaret", "Guido"] print(chunk(players, 3)) print(chunk([1, 2, 3, 4], 2)) print(chunk([], 3))
output
[['Ada', 'Linus', 'Grace'], ['Alan', 'Hedy', 'Margaret'], ['Guido']] [[1, 2], [3, 4]] []
How it works
range(0, len(items), size)counts up in steps ofsize. For 7 players and a size of 3, it gives the start positions 0, 3 and 6.items[start:start + size]cuts out one chunk. A slice that goes past the end of the list stops at the end without an error, so the last chunk is['Guido'].- An empty list gives no start positions, so the result is an empty list.
- A size of 0 makes
range()raiseValueError: range() arg 3 must not be zero, and a negative size returns an empty list with no error. The function checks the size first and gives a clear message.
Another way: itertools.batched()
Python 3.12 added batched() to the itertools module. It gives each chunk as a tuple:
python
from itertools import batched for team in batched(["Ada", "Linus", "Grace", "Alan", "Hedy"], 2): print(team)
output
('Ada', 'Linus')
('Grace', 'Alan')
('Hedy',)('Hedy',) is a tuple with one item. The comma is what makes it a tuple.