This concise, straight-to-the-point article will walk you through a couple of different approaches to splitting a given Python list into equally sized chunks (the last chunk might contain fewer elements than others if the length of the original list is not evenly divisible by the number of chunks).
The size of each chunk is fixed
This technique is useful when the size of each resulting chunk is predetermined, but the number of chunks is unknown.
The main idea here is to use list comprehension to iterate over the list indices from 0 to the length of the list with a step size of n
(the size of each chunk). For each index i
, use the slice notation list[i:i+n]
to extract a sublist of length n
from the original list and append it to the resulting list.
Example:
# Define the original list and the chunk size
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
n = 3
# Use list slicing and list comprehension to split the list into chunks
chunks = [my_list[i:i+n] for i in range(0, len(my_list), n)]
# Print the resulting list of chunks
print(chunks)
Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11]]
You can also define a reusable function like this:
def split_list_into_chunks(input_list, chunk_size):
return [input_list[i:i+chunk_size] for i in range(0, len(input_list), chunk_size)]
The number of ouput chunks is fixed
In case you want to get a certain number of chunks (the size of each chunk will depend on the length of the input list), then this is the solution for you. The steps are:
- Determine the chunk size by dividing the length of the list by the desired number of chunks.
- Use a list comprehension to iterate over the list and create sublists of the specified chunk size.
- Handle the case when the length of the list is not evenly divisible by the chunk size by appending the remaining elements to the last chunk.
- Return the list of chunks.
Code example:
import math
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
# Split in 4 chunks
num_chunks = 4
# Calculate the chunk size as an integer
chunk_size = math.ceil(len(my_list) / num_chunks)
chunks = [my_list[i:i + chunk_size] for i in range(0, len(my_list), chunk_size)]
print(chunks)
Output:
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15]]
To simplify the task in the future, we can create a reusable function like this:
import math
def divide_list_into_chucks(input_list, num_chunks):
chunk_size = math.ceil(len(input_list) / num_chunks)
return [input_list[i:i + chunk_size] for i in range(0, len(input_list), chunk_size)]
That’s it. Happy coding!