Unexpected Size of Python Objects in Memory
In this article, we will discuss unexpected size of python objects in Memory.
Python Objects include List, tuple, Dictionary, etc have different memory sizes and also each object will have a different memory address. Unexpected size means the memory size which we can not expect. But we can get the size by using getsizeof() function. This will return the memory size of the python object. This function is available in the sys module so we need to import it.
Syntax:
sys.getsizeof(object)
Example 1: Python code to get the unexpected size of string object
A string with a single character will consume 50 bytes, then after 1 character, it will consume n character bytes.
Example:
‘e’ will consume – 50
‘eo’ will consume – 51
‘eoo’ will consume – 52
Python3
import sys
print (sys.getsizeof( 'g' ))
print (sys.getsizeof( 'ge' ))
print (sys.getsizeof( 'gee' ))
print (sys.getsizeof( 'geek' ))
print (sys.getsizeof( 'geeks' ))
|
Output:
50
51
52
53
54
Example 2: Python program to get the unexpected size of integer object
Integer object will take 28 bytes
Python3
import sys
print (sys.getsizeof( 123 ))
print (sys.getsizeof( 21 ))
|
Output:
28
28
Example 3: Python code to get unexpected size of list object
We can define the list as []. An empty list will consume 72 bytes and consume extra 8 bytes for each element.
[] – 72
[1] – 72 + 8 = 80
[1,2] – 72 +8 + 8 =88
Python3
import sys
print (sys.getsizeof([]))
print (sys.getsizeof([ 2 ]))
print (sys.getsizeof([ 22 , 33 ]))
|
Output:
72
80
88
Example 4: Get unexpected size of the dictionary object
This object will consume 248 bytes irrespective of the number of items.
Python3
import sys
print (sys.getsizeof({}))
print (sys.getsizeof({ 'k' : 2 }))
print (sys.getsizeof({ 'k' : 2 , 'h' : 45 }))
|
Output:
248
248
248
Last Updated :
28 Nov, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...