Here’s an easy way to find the length of a NumPy array.
Array length
To calculate the length of the array, just use the Numpy size method.
import numpy as np my_array = np.array([[1,2,3],[4,5,6], [7,8,9],[10,11,12]]) print(f"Length of my array equals: {my_array.size}")
As an output, you get 12 as the length of the array.
Array shape
Now you know the length, but this information might not be enough for you. Let’s see the shape of the array.
import numpy as np my_array = np.array([[1,2,3],[4,5,6], [7,8,9],[10,11,12]]) print(f"Shape of my array: {my_array.shape}")
The shape of an array is 4 x 3, which is 12 in total. This is the output which gives you more information about the size of an array. You just need to remember that to get the length of an array, you need to multiply the output of the shape method.
Array size
Knowing the shape of the array is only the point of view. You might be interested in what the actual size of the array is from the storage point of view. This is how you get information about how many bytes your array consumes:
import numpy as np my_array = np.array([[1,2,3],[4,5,6], [7,8,9],[10,11,12]]) print(f"The array is using {my_array.nbytes} bytes.")
Thanks to the nbytes method, you know that the array is using 48 bytes.
This is how you get the full picture of the size, length, shape, and number of bytes the array requires.