Quick Tip: Do you Know How Much Memory Your Python Objects Use?

Esther Vaati
2 min readFeb 9, 2022

Find memory used by Python objects

Photo by Markus Spiske on Unsplash

In comparison to other languages, Python is not the fastest programming language. Knowing how much memory your application uses is essential to ensure that you don’t slow down your server and also your Python application works hassle-free on mobile devices.

Data structures have the most impact on memory in Python applications. But how do you measure memory?. Memory is measured in bits and bytes.
To find the size of memory used by a Python object, we will use sys.getsizeof function. getsizeof will return the size of your Python object in bytes. This function looks like this:

sys.getsizeof(object[, default])

Since everything in Python is an object, only the memory consumption directly attributed to the object is accounted for.

Lets see how different objects in Python vary in terms of memory size.

1 .Memory size of a String

import sysmy_string = "I love Python"mem = sys.getsizeof(my_string)print(mem)

The output is

62

2 .Memory size of a List

import sysmy_list = ['python','ruby','Go','Javascript','Java']mem = sys.getsizeof(my_list)print(mem)

The output is

96

3 .Memory size of a Tuple

import sysmy_tuple = ('python','ruby','Go','Javascript','Java')mem = sys.getsizeof(my_tuple)print(mem)

The output is

80

As you can see above the list and the tuple contain the same number of elemenrts but the list takes more memory than the tuple.

4 .Memory size of a Dictionary

import sysmy_dict = {"name" : "steve", "age":27}mem = sys.getsizeof(my_dict)print(mem)

The output is

232

5 .Memory size of a Set

import sysmy_set = {'python','ruby','Go','Javascript','Java'}mem = sys.getsizeof(my_set)print(mem)

The output is

728

6 .Memory size of a Function

import sysdef my_func(a,b):    return a+bmem = sys.getsizeof(my_func(2,3))print(mem)

The output is

28

6 .Memory size of Integers

import sysinte = 120mem = sys.getsizeof(inte)print(mem)

The output is:

28

6 .Memory size of Floats

import sysfloa = 120.478mem = sys.getsizeof(floa)print(mem)

The output is:

24

Conclusion

To understand more about Memory management, refer to the Python docs.

--

--

Esther Vaati
Esther Vaati

Written by Esther Vaati

Get practical JavaScript tips and code snippets delivered to your inbox. Join 1000 + developers who write better code. https://practicaljavascript.substack.com/

No responses yet