How do I split a list into equally-sized chunks?
Here is a function that takes a list and an integer
n and splits the list into
n equally sized chunks:
def split_list(input_list, chunk_size): # Get the length of the input list length = len(input_list) # Divide the length by the chunk size to get the number of sublists num_sublists = length // chunk_size # Use a for loop to split the input list into the appropriate number # of sublists for i in range(num_sublists): # Use slicing to get the i-th sublist yield input_list[i * chunk_size: (i + 1) * chunk_size] # Test the function input_list = [1, 2, 3, 4, 5, 6, 7, 8] for sublist in split_list(input_list, 3): print(sublist)
This will output:
[1, 2, 3] [4, 5, 6] [7, 8]
The function uses the
yield keyword to return a generator that produces the sublists. This means that the function will not create a new list with all of the sublists in it, but rather it will allow you to iterate over the sublists and do something with them one at a time. This can be more memory efficient if the input list is very large and you don't want to store all of the sublists in memory at once.