How to get the Size of an object in Python

avatar

Borislav Hadzhiev

Last updated: Jun 14, 2022

banner

Photo from Unsplash

How to get the Size of an object in Python #

Use the sys.getsizeof() method to get the size of an object, e.g. sys.getsizeof(my_object). The method takes an object argument and returns the size of the object in bytes. All built-in objects can be passed to the sys.getsizeof() method.

main.py
import sys print(sys.getsizeof(['a', 'b', 'c'])) # 👉️ 80 print(sys.getsizeof(10 ** 10)) # 👉️ 32

The sys.getsizeof method returns the size of an object in bytes.

The object can be any type of object and all built-in objects return correct results.

The size of an object includes the data stored by the object, the attributes, the methods, etc.

The getsizeof method only accounts for the direct memory consumption of the object, not the memory consumption of objects it refers to.

Note that some Python objects like lists and dictionaries may reference other objects and the getsizeof method doesn't account for that.

There is a recursive sizeof recipe in the official docs. It uses getsizeof recursively to find the size of an object and the objects it references.

The getsizeof() method calls the __sizeof__ method of the object, so it doesn't handle custom objects that don't implement it.

You can also import the getsizeof method directly instead of importing the entire sys module.

main.py
from sys import getsizeof print(getsizeof(['a', 'b', 'c'])) # 👉️ 80 print(getsizeof(10 ** 10)) # 👉️ 32
The size of an object is implementation-dependent. Different flavors of Python may use different internal data structures which means they would produce different results.

The sys.getsizeof() method takes an optional second argument - a default value to return if the object doesn't provide means to retrieve the size.

If no default value is provided and the object's size cannot be calculated, a TypeError is raised.

Here are examples of passing different types of objects to the getsizeof method.

main.py
from sys import getsizeof # 👇️ int print(getsizeof(0)) # 👉️ 24 # 👇️ float print(getsizeof(0.0)) # 👉️ 24 # 👇️ string print(getsizeof('')) # 👉️ 49 # 👇️ set print(getsizeof(set())) # 👉️ 216 # 👇️ tuple print(getsizeof(())) # 👉️ 40 # 👇️ list print(getsizeof([])) # 👉️ 56 # 👇️ dict print(getsizeof({})) # 👉️ 64 # 👇️ boolean print(getsizeof(True)) # 👉️ 28

Some objects like lists reserve space for more objects than they contain.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.