How to Split a List into Chunks in Python
Split a list into fixed-size sublists using a simple list comprehension with slicing.
Python code
8 linesdef chunk_list(lst, size):
"""Split a list into sublists of given size."""
return [lst[i:i + size] for i in range(0, len(lst), size)]
if __name__ == "__main__":
sample = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print(chunk_list(sample, 3))
Output
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]
How it works
range(0, len(lst), size) produces start indexes at 0, size, 2*size, etc. Slicing lst[i:i + size] extracts each chunk. The final chunk may be shorter if the list length isn't a multiple of size. This is O(n) and works for any sequence supporting slicing.
Common mistakes
- Using `range(len(lst))` and chunking by `i // size` which is slower and more complex
- Forgetting the last partial chunk when list length isn't divisible by size
- Mutating the original list with `del` or `pop` instead of creating new sublists
Variations
- Use `itertools.zip_longest` with an iterator trick for a lazy chunking generator
- Use `math.ceil(len(lst)/size)` and split with a loop for very large lists to save memory
Real-world use cases
- Batch rows from a database query into groups for paginated API responses.
- Split a large image dataset into mini-batches for model training loops.
- Divide a long list of email addresses into chunks for rate-limited sending.
Sponsored
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.