The Python getsizeof() function allows you to get the size (in bytes) of objects in your Python programs.

import sys

print(sys.getsizeof(3))
print(sys.getsizeof("hello"))
print(sys.getsizeof([0, 1, 2, 3]))

#Output:
28
54
120

When working with objects in Python, the ability to easily be able to get different pieces of information about the objects can be valuable.

One such piece of information which is valuable is the size of an object in memory.

When working with big datasets or collections of data with many elements, sometimes we need to be conscious of how much memory we are using.

The Python sys module getsizeof() function returns the size of a given object in bytes. The object can be any type of object.

Below are three examples showing you how to use getsizeof() in your Python code.

import sys

print(sys.getsizeof(3))
print(sys.getsizeof("hello"))
print(sys.getsizeof([0, 1, 2, 3]))

#Output:
28
54
120

Hopefully this article has been useful for you to learn how to use the Python getsizeof() function.

Categorized in:

Python,

Last Update: March 12, 2024