How to Get NumPy Array Length

In Python Numpy you can get array length/size using numpy.ndarray.size and numpy.ndarray.shape properties. The size property gets the total number of elements in a NumPy array. The shape property returns a tuple in (x, y).

You can get the length of the multi-dimensional array with the shape property in Python. In this article, we’ll explain several ways of how to get Numpy array length with examples by using properties like numpy.ndarray.size and numpy.ndarray.shape with examples.

1. Quick Examples to Get NumPy Array Length

If you are in a hurry, below are some quick examples of getting Python NumPy array size.


# Below are a quick example

# Example 1: Use numpy.size Property 
arr = np.array([1,3,6,9,12,15,20,22,25])
print(arr.size)

# Example 2: Using on 2-d array
arr = np.array([[1,3,6],[9,12,15],[20,22,25]])
print(arr.size)

# Example 3: Use numpy.shape property
arr = np.array([[1,3,6],[9,12,15],[20,22,25]])
print(arr.shape)

2. Use NumPy.size to Get Length

You can use ndarray.size property to get the total number of elements (length) in a NumPy array. Let’s create a NumPy array and use this to get the number of elements from one-dimensional arrays.


import numpy as np

# Example 1: Use numpy.size Property 
arr = np.array([1,3,6,9,12,15,20,22,25])
print(arr.size)

# OutPut
#9

In the below code, you get the number of elements in the multi-dimensional array with the ndarray.size property in Python. It also gives us the value 9 because the total number of elements is the same as in the previous example. This is the reason why this method is not suitable for multi-dimensional arrays.


# Example 2: Use numpy.size property to get length of a NumPy array
array = np.array([[1,3,6],[9,12,15],[20,22,25]])
print(array.size)

# OutPut
#9

3. Use NumPy.shape to get Length

So for multi-dimensional NumPy arrays use ndarray.shape function which returns a tuple in (x, y), where x is the number of rows and y is the number of columns in the array. You can now find the total number of elements by multiplying the values in the tuple with each other. This method is preferred over the previous method because it gives us the number of rows and columns.


# Example 3: Use numpy.shape property
arr = np.array([[1,3,6],[9,12,15],[20,22,25]])
print(arr.shape)

# Output
#(3, 3)

4. Conclusion

In this article, I have explained how to get Python Numpy array length/size or shape using ndarray.shape, ndarray.size properties with examples. By using the size property you can get the size of the array however it is not suitable to get the length of the multi-dimensional array. In order to get the multi-dimensional array size use the shape property which returns the tuple(x,y)

Happy Learning!!

You May Also Like

References

NumPy array length

Leave a Reply

You are currently viewing How to Get NumPy Array Length