Source Code:
(back to article)
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)
Result:
Report an issue