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:

Download  Run Code

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.

Download  Run Code

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:

Download  Run Code

 
This can be shortened with the iter() function:

Download  Run Code

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.

Download Code

That’s all about partitioning a list into chunks of a given size in Python.