Open In App

Unexpected Size of Python Objects in Memory

Improve
Improve
Like Article
Like
Save
Share
Report

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 module
import sys
  
# get the size of the given string
print(sys.getsizeof('g'))
  
# get the size of the given string
print(sys.getsizeof('ge'))
  
# get the size of the given string
print(sys.getsizeof('gee'))
  
# get the size of the given string
print(sys.getsizeof('geek'))
  
# get the size of the given string
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 module
import sys
  
# get the size of the given integer
print(sys.getsizeof(123))
  
# get the size of the given integer
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 module
import sys
  
# get the size of empty list
print(sys.getsizeof([]))
  
# get the size of list with one element
print(sys.getsizeof([2]))
  
# get the size of list with two elements
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 module
import sys
  
# get the size of empty dictionary
print(sys.getsizeof({}))
  
# get the size of dictionarydictionary with one element
print(sys.getsizeof({'k': 2}))
  
# get the size of list with two elements
print(sys.getsizeof({'k': 2, 'h': 45}))


Output:

248
248
248


Last Updated : 28 Nov, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads