How to Split a List into Equally-Sized Chunks in Python

Have you ever had a situation where you needed to split a list into equally-sized chunks in your Python program? In this article, we'll explore various methods to solve this problem.

Method 1: Using List Slicing

One simple and straightforward way to split a list into equal parts is by using list slicing. Here's how you can do it:

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

# Usage example
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunked_list = chunk_list(my_list, 3)
print(chunked_list)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In the above code snippet, we define a function chunk_list that takes two parameters: lst (the original list) and chunk_size (the size of each chunk). The function then uses list slicing with a step size of chunk_size to create chunks of equal size.

Method 2: Using itertools.islice

If you prefer a more concise solution, you can make use of the islice function from the itertools module. Here's an example:

from itertools import islice

def chunk_list(lst, chunk_size):
    it = iter(lst)
    return list(iter(lambda: list(islice(it, chunk_size)), []))

# Usage example
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunked_list = chunk_list(my_list, 3)
print(chunked_list)
# Output: [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10]]

In this method, we first convert the input list into an iterator using the iter function. Then, we use a lambda function with islice to create equal-sized chunks until the iterator is exhausted.

Method 3: Using numpy.array_split

If you have the numpy library installed, you can take advantage of the array_split function to split a list into equal parts. Here's how:

import numpy as np

def chunk_list(lst, chunk_size):
    return np.array_split(lst, len(lst) / chunk_size)

# Usage example
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
chunked_list = chunk_list(my_list, 3)
print(chunked_list)
# Output: [array([1, 2, 3]), array([4, 5, 6]), array([7, 8, 9]), array([10])]

By using array_split from numpy, we can split the list into equal-sized chunks, even if the length of the list is not evenly divisible by the chunk size.

Conclusion

In this article, we explored multiple methods to split a list into equally-sized chunks in Python. We demonstrated three different approaches: using list slicing, itertools.islice, and numpy.array_split. Depending on your preference and the requirements of your program, you can choose the method that suits you best.

Remember to consider the size of your list, the chunk size, and whether you have the numpy library installed when selecting the solution that is right for you.