Get the Size of a NumPy Array in Python

You can see this topic in two ways – determining the number of elements in a NumPy array or getting the memory size of the array. Let’s discuss this two.

Finding the Number of Elements in a NumPy Array

We will discuss three methods in this Section. Your array’s dimension and the used case will determine your chosen method.

The dimensionality of data is the number of attributes a dataset has. The following Figure shows 1, 2, and 3-dimensional arrays.

Method 1: Using array.shape function

This function shows the number of elements along each dimension of the array. Here are some examples,

Output:

(4, 3)
(3, 2, 4)

As shown in the output, arr1 has the shape of (4, 3) – 4 elements along the first dimension and 3 on the second.

Method 2: Using the len() function

This is the best method for finding the size of a 1-dimensional NumPy array.

If you are dealing with a multi-dimensional array, len() only shows the number of elements along the first dimension. For example,

Output:

5
2
2

In multi-dimensional arrays, like arr2 and arr3, the function returns the size of the first dimension only.

Note: the output of len(array) is always equivalent to arr.shape[0].

Method 3: Using array.size NumPy attribute

This method returns the count of all elements in the array irrespective of the dimension of the array. For example,

Output:

5
6
12

Method 4: Using np.shape() and np.prod() functions

As discussed in Method 1, the np.shape() function returns the size of each array dimension. If we want to get the actual number of elements in an array, we can simply multiply the values of np.shape() using the np.prod() function. Here are two examples.

Output:

Shape of arr1:  10
Size of arr1:  10
Shape of arr2:  (3, 4)
Number of elements in arr2:  12

Determining the Memory Size of a NumPy Array

This Section discusses two methods of determining the amount of memory a NumPy array takes.

Method 1: Using array.size and array.itemsize

This method takes the number of elements in an array and multiplies it with the amount of memory each item takes (derived by array.itemsize function) to get the total memory size taken by the array.

Output:

Size of each int64 item: 4

The memory size of arr1: 17408

The memory size of one uint16 item: 2

Total memory size taken by arr2: 8704

Method 2: Using array.nbytes

This method outputs the amount of memory a NumPy array uses in bytes. For example,

Output:

Memory size of arr1:  34816
Memory taken by arr2:  8704

You can also use the following table to convert bytes into other memory units.

For example,

Output:

Memory taken in bytes 8000000
Memory taken in MBs 7.62939453125
Memory taken in GBs 0.007450580596923828

Conclusion

This guide discussed different methods for determining the size of a NumPy Array – size being the number of elements of the amount of memory it takes to store the array.