Partition a list into chunks of a given size in Python
This post will discuss how to partition a list into chunks of the given length n in Python.
For example:
Input: [1, 2, 3, 4], n = 2
Output: [[1, 2], [3, 4]]
If the sequence’s length is not evenly divisible by the given length, we should fill the last partition with leftover elements.
Input: [1, 2, 3, 4, 5], n = 2
Output: [[1, 2], [3, 4], [5]]
Following are the different ways to partition a list into equal-length chunks in Python:
1. Using Slicing
A simple solution is to write a generator that yields the successive chunks of specified size from the list. This can be easily achieved with slicing, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
def partition(l, n): for i in range(0, len(l), n): yield l[i:i + n] if __name__ == '__main__': l = list(range(1, 10)) n = 3 chunks = list(partition(l, n)) print(chunks) |
2. Using List Comprehension
Alternatively, you can use list comprehension. This creates a new list where each list element results from some operation applied to each member.
|
1 2 3 4 5 6 7 8 |
if __name__ == '__main__': l = list(range(1, 10)) n = 3 chunks = [l[i:i + n] for i in range(0, len(l), n)] print(chunks) |
3. Using itertools module
Python itertools module offers the islice() function that creates a slice from the list. Here’s a generator to accomplish this:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import itertools def partition(l, size): for i in range(0, len(l), size): yield list(itertools.islice(l, i, i + size)) if __name__ == '__main__': l = list(range(1, 10)) n = 3 chunks = list(partition(l, n)) print(chunks) |
This can be shortened with the iter() function:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
import itertools def partition(l, size): it = iter(l) return iter(lambda: tuple(itertools.islice(it, size)), ()) if __name__ == '__main__': l = list(range(1, 10)) n = 3 chunks = list(partition(l, n)) print(chunks) |
4. Using toolz.itertoolz module
Finally, you have the toolz.itertoolz module that already has the partition() function to split the sequence into tuples of a certain length.
|
1 2 3 4 5 6 7 8 9 10 |
from toolz import partition if __name__ == '__main__': l = list(range(1, 10)) n = 3 chunks = list(partition(n, l)) print(chunks) |
That’s all about partitioning a list into chunks of a given size in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)