Python

NumPy np Array Length

In this article, we will discuss how you can get the size of a NumPy array. First, it is good to note that the collection size is determined by the number of elements in the array.

Let us discuss.

Size Property

NumPy provides the size property in an array that allows you to fetch the total number of elements within the specified array variable.

Consider the example code shown below:

import numpy as np
arr = np.array([1,2,3,4,5])
print(f"size: {arr.size}")

In the above code, we start by importing the numpy package with the alias of np.

Next, we create a one-dimensional array holding five elements. Then, using the arr.size property, we fetch the size of the array as shown in the output below:

size: 5

Although the size property works great for one-dimensional arrays, it falls back short for multi-dimensional arrays.

The code below illustrates this:

arr = np.array([[1,2,3], [4,5,6]])
print(f"size: {arr.size}")

The code above uses the size property to fetch the size of a 2d array. The resulting value is as shown below:

size: 6

Although it does return the total number of elements in the provided array, it does not accurately depict the size of the 2D array.

NumPy Shape()

To solve the issue encountered with the size property, we need to use the shape() function.

The shape() function is beneficial as it returns the number of elements in the provided array in each dimension.

This makes it handy when working with multi-dimensional arrays as it returns a tuple with the number of elements in each dimension. For example, in a 2D array,  the function should return the number of elements in the form (x, y), where x is the number of elements in the rows and y is the number of elements in the column.

Consider the previous example:

arr = np.array([[1,2,3], [4,5,6]])
print(f"size: {np.shape(arr)}")

In this case, the function should return:

size: (2, 3)

We have an array with two rows and three columns in this case.

This gives a more accurate depiction of the shape and size of the provided array.

The same case applies to 3d arrays. An example is shown below:

arr = np.array([[[1,2,3], [4,5,6], [7,8,9]]])
print(f"size: {np.shape(arr)}")

The above code should return the array shape as:

size: (1, 3, 3)

Conclusion

In this article, we discussed NumPy array sizes and how to use various NumPy properties and functions to get the size and shape of an array.

Thanks for reading & See you in the next one!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list