How to Get the Length of a NumPy Array

Here’s an easy way to explore how to obtain the length, shape, and size (in bytes) of a NumPy array.

Numpy array length

Getting the Length of a NumPy Array

In NumPy, you can use the .size attribute to get the total number of elements in an array.

For example, the following code creates an array with 12 elements:

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}")

Numpy array length

The output of the .size attribute is 12, indicating the total number of elements in the array.

Understanding Array Shape

If you want to understand how the elements are structured, you can use the .shape attribute to find the dimensions 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}")

Numpy array shape

The shape of the array is 4 x 3, indicating it has 4 rows and 3 columns, which multiply to a total of 12 elements. This shape detail helps you understand the array’s dimensions, not just the total element count.

See also  Ultimate tutorial on how to round in Numpy

Calculating Array Size in Bytes

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.")

numpy bytes nbytes

Thanks to the nbytes method, you know that the array is using 48 bytes.

See also  How to generate diagonal array in Numpy?

This is how you get the full picture of the size, length, shape, and number of bytes the array requires.

How to Get the Number of Bytes Used by a NumPy Array

In NumPy, you can use the nbytes method to get the number of bytes used by an array. The nbytes method returns the total number of bytes used to store the elements of the array.

See also  Managing BufferError: Understanding Buffer Interface in NumPy

For example, the following code creates an array with 12 elements:

import numpy as np

my_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]])

print(my_array.nbytes)

The output of the nbytes method is 48, which is the number of bytes used to store the elements of the array.