w3resource

NumPy: Find the number of elements of an array, length of one array element in bytes


Array Elements Count & Memory Usage

Write a NumPy program to find the number of elements in an array. It also finds the length of one array element in bytes and the total bytes consumed by the elements.

Pictorial Presentation:

Python NumPy: Find the number of elements of an array, length of one array element in bytes

Sample Solution:

Python Code:

 # Importing the NumPy library with an alias 'np'
import numpy as np

# Creating an array 'x' with specified data type 'float64'
x = np.array([1, 2, 3], dtype=np.float64)

# Printing the size of the array 'x'
print("Size of the array: ", x.size)

# Printing the length of one array element in bytes
print("Length of one array element in bytes: ", x.itemsize)

# Printing the total bytes consumed by the elements of the array 'x'
print("Total bytes consumed by the elements of the array: ", x.nbytes)

Sample Output:

Size of the array:  3                                                  
Length of one array element in bytes:  8                               
Total bytes consumed by the elements of the array:  24

Explanation:

In the above code -

x = np.array([1,2,3], dtype=np.float64): Creates a NumPy array with elements 1, 2, and 3, and with the specified dtype of float64.

print("Size of the array: ", x.size): Prints the size (number of elements) of the array, which is 3 in this case.

print("Length of one array element in bytes: ", x.itemsize): Prints the length (size) of one array element in bytes, which is 8 bytes for a float64.

print("Total bytes consumed by the elements of the array: ", x.nbytes): Prints the total bytes consumed by the elements of the array, which is the size (3 elements) multiplied by the itemsize (8 bytes) = 24 bytes.

Python-Numpy Code Editor: