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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github