How to find size of an object in Python?
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 Object Actual Size Notes int 28 NA str 49 +1 per additional character (49+total length of characters) tuple 40 (Empty Tuple) +8 per additional item in tuple ( 40 + 8*total length of characters ) list 56 (Empty List) +8 per additional item in list ( 56 + 8*total length of characters ) set 216 0-4 take size of 216. 5-19 take size 728. 20th will take 2264 and so on… dict 232 0-5 takes size of 232. 6-10 size will be 360. 11th will take 640 and so on… func def 136 No 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