Python Program to Split a List into Chunks
Intermediate · Lists
Splitting a list into chunks means cutting it into smaller lists of a fixed size, for example to show results page by page or to put students into groups. If the list does not divide evenly, the last chunk is shorter.
Program
split_list_into_chunks.py
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
size = 3 # or: size = int(input("Enter the chunk size: "))
chunks = []
# Start a new chunk at index 0, 3, 6, 9, ...
for start in range(0, len(numbers), size):
chunks.append(numbers[start:start + size])
print("List:", numbers)
print(f"Chunks of {size}:")
for chunk in chunks:
print(chunk)
Output
List: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] Chunks of 3: [1, 2, 3] [4, 5, 6] [7, 8, 9] [10, 11]
How it works
range(0, len(numbers), size)gives the index where each chunk starts: 0, 3, 6 and 9.numbers[start:start + size]slices out up tosizeelements from that point.- A slice that runs past the end of the list simply stops at the end, so the last chunk,
[10, 11], has only two elements and no error occurs. - Each chunk is a new list, and the chunks are printed one per line.
Other ways to write it
Using a list comprehension
Using a list comprehension
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
size = 4
chunks = [numbers[i:i + size] for i in range(0, len(numbers), size)]
print(f"Chunks of {size}:", chunks)
Output
Chunks of 4: [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11]]
The same slicing written as one expression.
Using itertools.batched()
Using itertools.batched()
from itertools import batched
students = ["Riya", "Aman", "Kabir", "Meera", "Zoya", "Arjun", "Diya"]
for number, group in enumerate(batched(students, 3), start=1):
print(f"Group {number}:", list(group))
Output
Group 1: ['Riya', 'Aman', 'Kabir'] Group 2: ['Meera', 'Zoya', 'Arjun'] Group 3: ['Diya']
batched() (Python 3.12 or newer) hands out the chunks one at a time as tuples, which list() turns back into lists.
Try it yourself
Change size to 5 and then to 11, and predict how many chunks you will get each time.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises