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.


For more Practice: Solve these Related Problems:

  • Calculate the total number of elements and memory consumption of an array using its nbytes attribute.
  • Compare memory usage for arrays of the same shape but different dtypes.
  • Write a function that converts the memory size of an array to kilobytes and megabytes.
  • Verify element size by multiplying the number of elements with the itemsize and comparing to nbytes.

Python-Numpy Code Editor:

Previous: Write a NumPy program to find the real and imaginary parts of an array of complex numbers
Next: Write a NumPy program to test whether each element of a 1-D array is also present in a second array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.