Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Find out how much memory is being used by an object in Python

  • Last Updated : 23 Aug, 2021

In this article, we are going to see how to find out how much memory is being used by an object in Python. For this, we will use sys.getsizeof() function can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.

Syntax: sys.getsizeof(object*)

 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. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

Parameters: arg can be int, str, function, etc.



Returns: Size of the given object.

This function is versatile and can work with any data type and even a function. For this first sys module has to be imported and then the object in consideration is passed to the function. Given below are various implementations for different objects.

Example 1: Get the size of an integer. 

Python3




import sys
  
var = 1
  
print(sys.getsizeof(var))

Output:

28

Example 2: Get the size of an decimal.

Python3




import sys
  
var = 1.2
  
print(sys.getsizeof(var))

Output:

24

Example 3: Get the size of an String.

Python3




import sys
  
# string init
var1 = ""
var2 = "gfg"
var3 = "Welcome to gfg"
  
# get size of an object
print(sys.getsizeof(var1))
print(sys.getsizeof(var2))
print(sys.getsizeof(var3))

Output:



64
72
96

Example 4: Get the size of an List. 

Python3




# import module
import sys
  
# list init
var1 = []
var2 = [1]
var3 = [1, 2, 3, 4]
  
# check size of obj
print(sys.getsizeof(var1))
print(sys.getsizeof(var2))
print(sys.getsizeof(var3))

Output:

64
72
96

Example 5: Get the size of an Set. 

Python3




import sys
  
# set init
var1 = set([])
var2 = set([1, 2, 3, 4, 5])
  
# get size of object
print(sys.getsizeof(var1))
print(sys.getsizeof(var2))

Output:

224
736

Example 6: Get the size of an Dictionary. 

Python3




import sys
  
# dic
var1 = {'Apple':1}
var2 = {'Apple':1, 'ball': 2, 'cat':3
        'dog': 4, 'egg': 5, 'frog': 6}
  
# get the size of object
print(sys.getsizeof(var1))
print(sys.getsizeof(var2))

Output:

240
368

Example 7: Get the size of an Function. 

Python3




import sys
  
def func():
    pass
var = func
print(sys.getsizeof(var))

Output:

136



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!