Split an array into n parts of almost equal length in Python

In this tutorial, we are going to see how to split an array into n parts of almost equal length in Python. One of the approaches to this is by using an in-built function from the Numpy library. The array is a collection of data and is one of the data structures in Python.

First import the Numpy library to use in the code:

import numpy as np

Define the array of any data type with some elements.

arr = np.array([4,5,6,7,8,9,10])

array_split( ): splits the Numpy array into almost equal-length subparts

array_split(arr, n) is a function from the Numpy library which is used to split the array or list into several subarrays. You need to pass the array(arr) and the number of subarrays you want (n). This function splits the array into almost equal-length subparts.

Now using this function split the array

arr_split = np.array_split(arr, 3)

Now pass the array in the loop to print the subarrays. eg. for loop, while loop, etc.

for an in arr_split:


[4 5 6]
[7 8]
[ 9 10]


Also, refer to numpy. split | Split an array into multiple sub-array in Python

Leave a Reply

Your email address will not be published. Required fields are marked *