NumPy: Find the memory size of a NumPy array
NumPy: Array Object Exercise-33 with Solution
Write a NumPy program to find the memory size of a NumPy array.
Pictorial Presentation:
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:
Previous: Write a NumPy program to save a NumPy array to a text file.
Next: Write a NumPy program to create an array of ones and an array of zeros.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/numpy/python-numpy-exercise-33.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics