How do I split Python list into equally-sized chunks?

Better Stack Team
Updated on January 26, 2023

To split a list into equally sized chunks, you can use the grouper function from the itertools module.

Here's an example of how you can use it:

 
from itertools import zip_longest

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

# Example usage
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
n = 3
chunks = list(grouper(my_list, n))

print(chunks)

This will output the following list of chunks:

 
[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, None, None)]

You can also use list slicing to achieve the same result:

 
def split_list(my_list, chunk_size):
    return [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]

# Example usage
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunk_size = 3
chunks = split_list(my_list, chunk_size)

print(chunks)

This will output the following list of chunks:

 
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

You can choose the method that best fits your needs.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.

We are hiring.

Software is our way of making the world a tiny bit better. We build tools for the makers of tomorrow.

Explore all positions →