Python Program to Split a List Into Evenly Sized Chunks
Splitting a list into evenly sized chunks means dividing a given list into smaller sublists of equal length.
Python Code :
The Python program to splits a list into evenly sized chunks:
def split_list(lst, chunk_size): """ Split a list into evenly sized chunks. Args: lst: The list to be split. chunk_size: The size of each chunk. Returns: A list of lists where each sub-list is of size 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] chunked_list = split_list(my_list, 3) print(chunked_list)
In this program, we define a function split_list that takes two arguments: the list to be split (lst) and the size of each chunk (chunk_size). The function returns a list of lists where each sub-list is of size chunk_size.
We achieve this by using a list comprehension that iterates through the indices of the original list in steps of chunk_size. For each index, we create a sub-list that starts at that index and goes up to index + chunk_size. We do this until we’ve gone through the entire list.
In the example usage, we create a list of numbers and call the split_list function with a chunk size of 3. The resulting list of lists is then printed to the console. Output:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], ]