PythonMastery
Python programs · Lists · beginner

Split a list into chunks in Python

Split a list into smaller lists of a fixed size in Python with range() and slicing, and with itertools.batched() in Python 3.12 and later.

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

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.

Learn the idea: Lists & Sequences, Functions & Scoping, Itertools: Composable Iterator Building Blocks