Python Program - Split a List Into Evenly Sized Chunks

ht‮‬tps://www.theitroad.com

Here's a Python program that splits a list into evenly sized chunks:

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

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

Output:

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

In this program, the split_list() function takes two arguments: the list to be split (lst) and the size of each chunk (chunk_size). The function returns a new list that contains the original list split into evenly sized chunks.

The list comprehension in the split_list() function uses a slice notation to extract each chunk from the original list. The range() function is used to generate a sequence of starting indexes for each chunk. The len() function is used to get the total length of the original list. The chunk_size argument is used to specify the step size for the range function.

Finally, the print() function is used to display the resulting list of chunks.