Numpy Array Length

Numpy Array Length

Numpy is a powerful library in Python that provides support for large, multi-dimensional arrays and matrices, along with a collection of mathematical functions to operate on these arrays. One common operation you might need to perform when working with Numpy arrays is determining the length of the array.

In this article, we will explore how to find the length of a Numpy array and discuss various methods to achieve this.

Finding the length of a Numpy array

The length of a Numpy array can be determined by using the len() function, which returns the number of elements in the given array. It’s important to note that the length of a Numpy array is the total number of elements in the array, not the number of dimensions.

Let’s explore some examples to understand how to find the length of a Numpy array:

Example 1:

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(len(arr))

Output:

Numpy Array Length

In this example, we have created a Numpy array arr with 5 elements, and then used the len() function to find its length, which is 5.

Example 2:

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(len(arr))

Output:

Numpy Array Length

Here, we have created a 3×3 Numpy array arr, and by using the len() function, we get the length of the array, which is 3.

Example 3:

import numpy as np

arr = np.array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
print(len(arr))

Output:

Numpy Array Length

In this case, we have created a 2x2x2 Numpy array arr, and the length is determined to be 2.

Methods to find the length of a Numpy array

Apart from using the len() function, there are a few other methods to find the length of a Numpy array:

Method 1: Using the size attribute

The size attribute of a Numpy array returns the total number of elements in the array. This can be used to determine the length of the array.

import numpy as np

arr = np.array([1, 2, 3, 4, 5])
print(arr.size)

Output:

Numpy Array Length

Method 2: Using the shape attribute

The shape attribute of a Numpy array returns a tuple representing the dimensions of the array. The length of the array can be obtained by taking the first element of this tuple.

import numpy as np

arr = np.array([[1, 2, 3], [4, 5, 6]])
print(arr.shape[0])

Output:

Numpy Array Length

Conclusion of Numpy array length

In this article, we have discussed how to find the length of a Numpy array and explored different methods to achieve this. Understanding the length of a Numpy array is important for performing various operations on the data it contains. By utilizing the len(), size and shape attributes, you can easily determine the length of any Numpy array.

Like(1)