How to segment a Python array (or list) into smaller sub-arrays

Published on Aug. 22, 2023, 12:15 p.m.

To segment a Python array (or list) into smaller sub-arrays, you can use various techniques such as list comprehension or the numpy.array_split() method from the NumPy library. Here’s an example of using list comprehension to split an array into groups of three:

my_array = [1, 2, 3, 4, 5, 6, 7, 8, 9]
segment_size = 3
segments = [my_array[i:i+segment_size] for i in range(0, len(my_array), segment_size)]
print(segments)

In this example, we use list comprehension to iterate over the my_array list in steps of segment_size, using the range() function to generate the list of starting indices for each segment. We slice the list to extract the sub-array for each segment using the i index and the i+segment_size index, and add the extracted sub-array to the segments list.

Alternatively, you can use NumPy’s array_split() function to split the array into equal-sized sub-arrays, like this:

import numpy as np

my_array = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
segment_size = 3
segments = np.array_split(my_array, len(my_array) / segment_size)
print(segments)

In this example, we first convert the my_array list into a NumPy array, and then use the np.array_split() method to split the array into equal-sized sub-arrays using the len(my_array) / segment_size argument. The method returns a list of NumPy arrays, which we print to the console.

Tags: