Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to find size of an object in Python?

  • Difficulty Level : Basic
  • Last Updated : 05 Jan, 2022

Use of sys.getsizeof() 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.

Note: Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

Examples:  

Input: 
# Any Integer Value
sys.getsizeof(4) 

Expected Output: 4 bytes (Size of integer is 4bytes)

Actual Output: 28 bytes

Here’s how we can interpret the actual output. Have a look at this table below: 

Type of ObjectActual SizeNotes
int28NA
str49+1 per additional character (49+total length of characters)
tuple40 (Empty Tuple)+8 per additional item in tuple ( 40 + 8*total length of characters )
list56 (Empty List)+8 per additional item in list ( 56 + 8*total length of characters )
set2160-4 take size of 216. 5-19 take size 728. 20th will take 2264 and so on…
dict2320-5 takes size of 232. 6-10 size will be 360. 11th will take 640 and so on…
func def136No attributes and default arguments

Example:

Python3




import sys
 
a = sys.getsizeof(12)
print(a)
 
b = sys.getsizeof('geeks')
print(b)
 
c = sys.getsizeof(('g', 'e', 'e', 'k', 's'))
print(c)
 
d = sys.getsizeof(['g', 'e', 'e', 'k', 's'])
print(d)
 
e = sys.getsizeof({1, 2, 3, 4})
print(e)
 
f = sys.getsizeof({1: 'a', 2: 'b', 3: 'c', 4: 'd'})
print(f)

Output:

28
54
88
104
224
240
My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!