How to Group a List into Chunks in Python
Split a list into smaller groups of a fixed size using a reusable function with a default parameter.
Python code
14 linesdef make_groups(numbers, group_size=2):
"""Splits a list into smaller groups of a given size."""
groups = []
for i in range(0, len(numbers), group_size):
groups.append(numbers[i:i + group_size])
return groups
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7]
print("Default size (2):", make_groups(data))
print("Custom size (3):", make_groups(data, 3))
print("Custom size (1):", make_groups(data, 1))
Output
Default size (2): [[1, 2], [3, 4], [5, 6], [7]]
Custom size (3): [[1, 2, 3], [4, 5, 6], [7]]
Custom size (1): [[1], [2], [3], [4], [5], [6], [7]]
How it works
The make_groups function uses a for loop with range(0, len(numbers), group_size) to step through the list in fixed-size jumps. Each slice numbers[i:i + group_size] grabs one group, including a possibly shorter final slice when the list length isn't a multiple of the group size. The group_size=2 default means callers can use the function with just one argument, while still allowing a custom chunk size when needed. This pattern is a clean, beginner-friendly way to separate function logic from the main script using an if __name__ == "__main__" block.
Common mistakes
- Using `group_size` as 0, which causes a `ValueError` from zero-step in `range()`
- Assuming all groups are the same size when the list length isn't divisible by the group size
- Mutating the original list inside the loop instead of creating new slices
Variations
- Use a list comprehension: `[numbers[i:i + group_size] for i in range(0, len(numbers), group_size)]`
- Return an iterator with a generator expression to handle large lists lazily
Real-world use cases
- Batching database records into chunks for bulk inserts or row processing.
- Splitting a large API payload into pages for paginated requests.
- Grouping log entries into time buckets for batch analysis.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.