Skip to content
Related Articles

Related Articles

Find the memory size of a NumPy array
  • Last Updated : 02 Sep, 2020

In this post, we will see how to find the memory size of a NumPy array. So for finding the memory size we are using following methods:

Method 1: Using size and itemsize attributes of NumPy array.

size: This attribute gives the number of elements present in the NumPy array.

itemsize: This attribute gives the memory size of one element of NumPy array in bytes.

Let’s see the examples:



Example 1:

Python3




# import library
import numpy as np
  
# create a numpy 1d-array
x = np.array([100,20,34])
  
print("Size of the array: ",
      x.size)
  
print("Memory size of one array element in bytes: ",
      x.itemsize)
  
# memory size of numpy array in bytes
print("Memory size of numpy array in bytes:",
      x.size * x.itemsize)

Output:

Size of the array:  3
Memory size of one array element in bytes:  4
Memory size of numpy array in bytes: 12

Example 2:

Python3




# import library
import numpy as np
  
# create a numpy 2d-array
x = np.array([[100, 20, 34],
              [300, 400, 600]])
  
print("Size of the array: ",
      x.size)
  
print("Memory size of one array element in bytes: ",
      x.itemsize)
  
# memory size of numpy array
print("Memory size of numpy array in bytes:",
      x.size * x.itemsize)

Output:

Size of the array:  6
Length of one array element in bytes:  4
Memory size of numpy array in bytes: 24

Method 2: Using nbytes attribute of NumPy array.

nbytes: This attribute gives the total bytes consumed by the elements of the NumPy array.



Let’s see the examples:

Example 1:

Python3




# import library
import numpy as np
  
# create numpy 1d-array
x = np.array([100, 20, 34])
  
print("Memory size of a NumPy array:",
      x.nbytes)

Output:

Memory size of a NumPy array: 12

Example 2:

Python3




# import library
import numpy as np
  
# create numpy 2d-array
x = np.array([[100, 20, 34],
              [300, 400, 600]])
  
print("Memory size of a NumPy array:",
      x.nbytes)

Output:

Memory size of a NumPy array: 24

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :