OneBite.Dev - Coding blog in a bite size

split an array into smaller arrays in python

Code snippet on how to split an array into smaller arrays in python

  def split_list(list_to_split, split_size): 
    output_list = [] 
    for i in range(0, len(list_to_split), split_size): 
        output_list.append(list_to_split[i:i + split_size]) 
    return output_list 

This piece of code takes a list (list_to_split) and splits it into smaller lists of a given size (split_size). It’s created by iterating through the list, taking each item and adding it to a new list. It then moves to the next item and adds it to the generated list, repeating this process until it has a list of the given size. When one list of the specified size is created, the code adds it to another list (output_list) and continues the process until it has gone through the entire input list. At the end of the process, the code returns the output_list containing all of the smaller lists.

python