w3resource

NumPy: Find the memory size of a NumPy array


Memory Size of Array

Write a NumPy program to find the memory size of a NumPy array.

Pictorial Presentation:

Python NumPy: Find the memory size of a NumPy array

Sample Solution:

Python Code:

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

# Creating a 4x4 array filled with zeros
n = np.zeros((4,4))

# Calculating the total memory consumed by the array and displaying it in bytes
print("%d bytes" % (n.size * n.itemsize))

Sample Output:

128 bytes 

Explanation:

The above code creates a NumPy array filled with zeros and calculates its memory size in bytes.

n = np.zeros((4,4)): This statement creates a NumPy array n of shape (4, 4) filled with zeros. By default, the dtype is 'float64', meaning each element takes up 8 bytes of memory.

print("%d bytes" % (n.size * n.itemsize)): This statement calculates the total memory size of the array in bytes and prints it. The .size attribute returns the number of elements in the array (4 * 4 = 16), and the .itemsize attribute returns the memory size of one element in bytes (8 bytes for a float64). The product of these two values (16 * 8 = 128) gives the total memory size of the array in bytes.

Python-Numpy Code Editor: