How to partition a list into n nearly equal parts in Python
Divide a list into n contiguous chunks of nearly equal size using an average-length calculation that distributes the remainder evenly.
Python code
28 linesdef partition(lst, n):
"""Partition a list into n nearly equal contiguous parts."""
if n <= 0:
raise ValueError("n must be positive")
if not lst:
return [[] for _ in range(n)]
parts = []
avg = len(lst) / n
last_idx = 0.0
while last_idx < len(lst):
end_idx = int(round(last_idx + avg))
parts.append(lst[int(last_idx):end_idx])
last_idx = end_idx
# Ensure we return exactly n parts
while len(parts) < n:
parts.append([])
return parts
if __name__ == "__main__":
data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for n in range(1, 6):
result = partition(data, n)
print(f"n={n}: {result}")
Output
n=1: [[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]]
n=2: [[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]]
n=3: [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10]]
n=4: [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10]]
n=5: [[1, 2], [3, 4], [5, 6], [7, 8], [9, 10]]
How it works
The function computes the average chunk size as len(lst) / n and uses a floating-point boundary last_idx to decide where each chunk ends. By rounding the cumulative average, longer parts appear early in the list and shorter parts later, keeping sizes within one element of each other. The final while loop guarantees the result has exactly n parts, even when the list length is smaller than n or zero. This approach is efficient—O(n) time—and avoids sorting or complex index math.
Common mistakes
- Using integer division (//) for avg, which truncates and loses the remainder distribution
- Forgetting to check for n <= 0, causing division by zero or infinite loops
- Not padding with empty lists when n exceeds the list length
- Assuming parts must be equal size when the list length is not divisible by n
Variations
- Use a simple slice-based approach: `[lst[i::n] for i in range(n)]` for non-contiguous parts
- For equal-size partitions with remainder handled differently, use `[lst[i::n] for i in range(n)]` but note it groups by element index not contiguous blocks
Real-world use cases
- Splitting a dataset into train/validation/test folds for cross-validation with near-balanced classes.
- Distributing a list of tasks across multiple worker processes or threads for parallel execution.
- Paginating long result lists into sequential pages of approximate equal size for API responses.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.