Check memory usage of your Python objects

With sys.getsizeof() you can check the memory usage of an object. To do so, first import the module sys:

import sys

mylist = range(0, 10000)
# 48

Woah… wait… why is this huge list only 48 bytes?

It’s because the range function returns an iterable object that only behaves like a list of numbers, but internally simply keeps count of the last iteration number. A range is magnitudes more memory efficient than using an actual list of numbers.

You can see for yourself by using a list comprehension to create an actual Python list of numbers from the same range:

import sys

myreallist = [x for x in range(0, 10000)]
# 87632

That’s roughly 87KB for 10,000 numbers.

Not very accurate

One thing to note: this method is not very accurate. sys.getsizeof will not recursively calculate the memory usage of all objects in a list or dictionary. So when requesting the size of a list, you request only the size of the list itself and all its references to the content, but the size of all those integers themselves is not taken into account. E.g., a Python integer takes up 28 bytes by itself:

>>> import sys
>>> sys.getsizeof(1)
>>> 10000 * 28

10K integers will take up an additional 280K or so bytes of memory, in addition to the list size of 87K.

Please share this article with others!

Python Courses

Are you enjoying this free tutorial? Please also have a look at my premium courses. They offer a superior user experience with small, easy-to-digest lessons and topics, progress tracking, quizzes to test your knowledge, and practice sessions. Each course will earn you a downloadable course certificate.

The Python Fundamentals Course For Beginners
Now for $29 (from $59)

Python Fundamentals I is a course for beginners that will get you started with Python in no time. Learn all the essentials, test your progress with quizzes and assignments, and bring it all together with the final course project!

Python Course for Beginners

Modules, Packages, And Virtual Environments
Now for $29 (from $59)

Python Fundamentals II covers creating your own modules and packages, using virtual environments and Python package managers to make your life as a programmer easier. Advance your productivity as a Python programmer!

Python Fundamentals 2

Leave a Comment

Share to...