Try this:

sys.getsizeof(object)

getsizeof() Return the size of an object in bytes. It calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

A recursive recipe

Answer from Uzer on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › python › how-to-find-size-of-an-object-in-python
How to find size of an object in Python? - GeeksforGeeks
July 17, 2023 - In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes.
Discussions

Object size
The sys.getsizeof() documentation says: Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to. Your code is only checking one level of objects in the object object. That probably explains the discrepancy you see. Note that the sys.getsizeof() documentation does point to a method to get a better estimate: See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents. but that link doesn't work for me at the moment. More on reddit.com
🌐 r/learnpython
2
2
May 24, 2024
How to get the size of data in a class instance?
Python 3.12 on Windows 10. I’m not a pro at Python, I’m still new with about 5 months experience. I have a custom class that is full of options for the program, and many other things. I use it to pass data to different functions as a single parameter. This idea works very well. More on discuss.python.org
🌐 discuss.python.org
0
0
August 21, 2024
Measure the Real Size of Any Python Object
d={} d[1]=d You should memoize a list of object IDs that you've looked at, return 0 if that object has already been tallied. More on reddit.com
🌐 r/Python
12
1
July 21, 2016
Memory Size of Python Data Structures
cool, didn't know u could do this don't name variables keywords though More on reddit.com
🌐 r/Python
14
15
August 10, 2022
Top answer
1 of 16
964

Just use the sys.getsizeof function defined in the sys module.

sys.getsizeof(object[, default]):

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError.

getsizeof calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents.

Usage example, in python 3.0:

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48

If you are in python < 2.6 and don't have sys.getsizeof you can use this extensive module instead. Never used it though.

2 of 16
659

How do I determine the size of an object in Python?

The answer, "Just use sys.getsizeof", is not a complete answer.

That answer does work for builtin objects directly, but it does not account for what those objects may contain, specifically, what types, such as custom objects, tuples, lists, dicts, and sets contain. They can contain instances each other, as well as numbers, strings and other objects.

A More Complete Answer

Using 64-bit Python 3.6 from the Anaconda distribution, with sys.getsizeof, I have determined the minimum size of the following objects, and note that sets and dicts preallocate space so empty ones don't grow again until after a set amount (which may vary by implementation of the language):

Python 3:

Empty
Bytes  type        scaling notes
28     int         +4 bytes about every 30 powers of 2
37     bytes       +1 byte per additional byte
49     str         +1-4 per additional character (depending on max width)
48     tuple       +8 per additional item
64     list        +8 for each additional
224    set         5th increases to 736; 21nd, 2272; 85th, 8416; 341, 32992
240    dict        6th increases to 368; 22nd, 1184; 43rd, 2280; 86th, 4704; 171st, 9320
136    func def    does not include default args and other attrs
1056   class def   no slots 
56     class inst  has a __dict__ attr, same scaling as dict above
888    class def   with slots
16     __slots__   seems to store in mutable tuple-like structure
                   first slot grows to 48, and so on.

How do you interpret this? Well say you have a set with 10 items in it. If each item is 100 bytes each, how big is the whole data structure? The set is 736 itself because it has sized up one time to 736 bytes. Then you add the size of the items, so that's 1736 bytes in total

Some caveats for function and class definitions:

Note each class definition has a proxy __dict__ (48 bytes) structure for class attrs. Each slot has a descriptor (like a property) in the class definition.

Slotted instances start out with 48 bytes on their first element, and increase by 8 each additional. Only empty slotted objects have 16 bytes, and an instance with no data makes very little sense.

Also, each function definition has code objects, maybe docstrings, and other possible attributes, even a __dict__.

Also note that we use sys.getsizeof() because we care about the marginal space usage, which includes the garbage collection overhead for the object, from the docs:

getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

Also note that resizing lists (e.g. repetitively appending to them) causes them to preallocate space, similarly to sets and dicts. From the listobj.c source code:

    /* This over-allocates proportional to the list size, making room
     * for additional growth.  The over-allocation is mild, but is
     * enough to give linear-time amortized behavior over a long
     * sequence of appends() in the presence of a poorly-performing
     * system realloc().
     * The growth pattern is:  0, 4, 8, 16, 25, 35, 46, 58, 72, 88, ...
     * Note: new_allocated won't overflow because the largest possible value
     *       is PY_SSIZE_T_MAX * (9 / 8) + 6 which always fits in a size_t.
     */
    new_allocated = (size_t)newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6);

Historical data

Python 2.7 analysis, confirmed with guppy.hpy and sys.getsizeof:

Bytes  type        empty + scaling notes
24     int         NA
28     long        NA
37     str         + 1 byte per additional character
52     unicode     + 4 bytes per additional character
56     tuple       + 8 bytes per additional item
72     list        + 32 for first, 8 for each additional
232    set         sixth item increases to 744; 22nd, 2280; 86th, 8424
280    dict        sixth item increases to 1048; 22nd, 3352; 86th, 12568 *
120    func def    does not include default args and other attrs
64     class inst  has a __dict__ attr, same scaling as dict above
16     __slots__   class with slots has no dict, seems to store in 
                    mutable tuple-like structure.
904    class def   has a proxy __dict__ structure for class attrs
104    old class   makes sense, less stuff, has real dict though.

Note that dictionaries (but not sets) got a more compact representation in Python 3.6

I think 8 bytes per additional item to reference makes a lot of sense on a 64 bit machine. Those 8 bytes point to the place in memory the contained item is at. The 4 bytes are fixed width for unicode in Python 2, if I recall correctly, but in Python 3, str becomes a unicode of width equal to the max width of the characters.

And for more on slots, see this answer.

A More Complete Function

We want a function that searches the elements in lists, tuples, sets, dicts, obj.__dict__'s, and obj.__slots__, as well as other things we may not have yet thought of.

We want to rely on gc.get_referents to do this search because it works at the C level (making it very fast). The downside is that get_referents can return redundant members, so we need to ensure we don't double count.

Classes, modules, and functions are singletons - they exist one time in memory. We're not so interested in their size, as there's not much we can do about them - they're a part of the program. So we'll avoid counting them if they happen to be referenced.

We're going to use a blacklist of types so we don't include the entire program in our size count.

import sys
from types import ModuleType, FunctionType
from gc import get_referents

# Custom objects know their class.
# Function objects seem to know way too much, including modules.
# Exclude modules as well.
BLACKLIST = type, ModuleType, FunctionType


def getsize(obj):
    """sum size of object & members."""
    if isinstance(obj, BLACKLIST):
        raise TypeError('getsize() does not take argument of type: '+ str(type(obj)))
    seen_ids = set()
    size = 0
    objects = [obj]
    while objects:
        need_referents = []
        for obj in objects:
            if not isinstance(obj, BLACKLIST) and id(obj) not in seen_ids:
                seen_ids.add(id(obj))
                size += sys.getsizeof(obj)
                need_referents.append(obj)
        objects = get_referents(*need_referents)
    return size

To contrast this with the following whitelisted function, most objects know how to traverse themselves for the purposes of garbage collection (which is approximately what we're looking for when we want to know how expensive in memory certain objects are. This functionality is used by gc.get_referents.) However, this measure is going to be much more expansive in scope than we intended if we are not careful.

For example, functions know quite a lot about the modules they are created in.

Another point of contrast is that strings that are keys in dictionaries are usually interned so they are not duplicated. Checking for id(key) will also allow us to avoid counting duplicates, which we do in the next section. The blacklist solution skips counting keys that are strings altogether.

Whitelisted Types, Recursive visitor

To cover most of these types myself, instead of relying on the gc module, I wrote this recursive function to try to estimate the size of most Python objects, including most builtins, types in the collections module, and custom types (slotted and otherwise).

This sort of function gives much more fine-grained control over the types we're going to count for memory usage, but has the danger of leaving important types out:

import sys
from numbers import Number
from collections import deque
from collections.abc import Set, Mapping


ZERO_DEPTH_BASES = (str, bytes, Number, range, bytearray)


def getsize(obj_0):
    """Recursively iterate to sum size of object & members."""
    _seen_ids = set()
    def inner(obj):
        obj_id = id(obj)
        if obj_id in _seen_ids:
            return 0
        _seen_ids.add(obj_id)
        size = sys.getsizeof(obj)
        if isinstance(obj, ZERO_DEPTH_BASES):
            pass # bypass remaining control flow and return
        elif isinstance(obj, (tuple, list, Set, deque)):
            size += sum(inner(i) for i in obj)
        elif isinstance(obj, Mapping) or hasattr(obj, 'items'):
            size += sum(inner(k) + inner(v) for k, v in getattr(obj, 'items')())
        # Check for custom object instances - may subclass above too
        if hasattr(obj, '__dict__'):
            size += inner(vars(obj))
        if hasattr(obj, '__slots__'): # can have __slots__ with __dict__
            size += sum(inner(getattr(obj, s)) for s in obj.__slots__ if hasattr(obj, s))
        return size
    return inner(obj_0)

And I tested it rather casually (I should unittest it):

>>> getsize(['a', tuple('bcd'), Foo()])
344
>>> getsize(Foo())
16
>>> getsize(tuple('bcd'))
194
>>> getsize(['a', tuple('bcd'), Foo(), {'foo': 'bar', 'baz': 'bar'}])
752
>>> getsize({'foo': 'bar', 'baz': 'bar'})
400
>>> getsize({})
280
>>> getsize({'foo':'bar'})
360
>>> getsize('foo')
40
>>> class Bar():
...     def baz():
...         pass
>>> getsize(Bar())
352
>>> getsize(Bar().__dict__)
280
>>> sys.getsizeof(Bar())
72
>>> getsize(Bar.__dict__)
872
>>> sys.getsizeof(Bar.__dict__)
280

This implementation breaks down on class definitions and function definitions because we don't go after all of their attributes, but since they should only exist once in memory for the process, their size really doesn't matter too much.

🌐
Envato Tuts+
code.tutsplus.com › home › python
Understand How Much Memory Your Python Objects Use | Envato Tuts+
May 20, 2022 - The standard library's sys module provides the getsizeof() function. That function accepts an object (and optional default), calls the object's sizeof() method, and returns the result, so you can make your objects inspectable as well.
🌐
Stack Abuse
stackabuse.com › bytes › determining-the-size-of-an-object-in-python
Determining the Size of an Object in Python
September 8, 2023 - For example, if your application is running out of memory and crashing, determining the size of objects can help you pinpoint the objects using up the most memory. This can be a lifesaver when you're dealing with memory-intensive tasks. Python provides a built-in function, sys.getsizeof(), which can be used to determine the size of an object.
🌐
Reddit
reddit.com › r/learnpython › object size
r/learnpython on Reddit: Object size
May 24, 2024 -

I am generating a fairly large object with the intention to store it in mongodb using GridFS. It turns out that the file size in MongoDB is huge (several hundred MBs) while the object size in python returns a fairly manageable size (roughly 5000 bytes) as measured by:

sum = 0
for d in dir(object):
  sum += sys.getsizeof(d) 

What am I missing here? The sum variable does seemingly underestimate true size, since a object size of 5000 bytes wouldn't theoretically require GridFS for storing. Is there a way to loop through all layers attributes in an object?

Thanks!

Find elsewhere
🌐
Codedamn
codedamn.com › news › python
How to Determine the Size of Objects in Python
July 2, 2023 - Instead, Python provides some tools and modules that let us interact with the memory manager indirectly and get information about the memory usage. Python provides a built-in module named 'sys' which has a method called 'getsizeof()' that can ...
🌐
GoShippo
goshippo.com › blog › measure-real-size-any-python-object
How to Measure the Real Size of Any Object in Python
April 14, 2025 - It uses sys.getsizeof internally and it turned out to be pretty easy to write once I figured out enough of the edge cases. I hope it helps the next time you need to accurately measure the size of an object! By the way, we’re hiring at Shippo! We work with Python, EmberJS, and PostgreSQL.
🌐
PyPI
pypi.org › project › objsize
objsize · PyPI
This process, often referred to as deep size calculation, is achieved through Python’s internal Garbage Collection (GC) mechanism. The objsize package is designed to ignore shared objects, such as None, types, modules, classes, functions, and lambdas, because they are shared across many instances. One of the key performance features of objsize is that it avoids recursive calls, ensuring a faster and safer execution. ... Calculate the size of the object including all its members in bytes.
      » pip install objsize
    
Published   Jan 18, 2026
Version   0.8.0
🌐
GeeksforGeeks
geeksforgeeks.org › find-out-how-much-memory-is-being-used-by-an-object-in-python
Find out how much memory is being used by an object in Python - GeeksforGeeks
April 13, 2023 - In python, the usage of sys.getsizeof() can be done to find the storage size of a particular object that occupies some space in the memory. This function returns the size of the object in bytes. It takes at most two arguments i.e Object itself.
🌐
Python.org
discuss.python.org › python help
How to get the size of data in a class instance? - Python Help - Discussions on Python.org
August 21, 2024 - Python 3.12 on Windows 10. I’m not a pro at Python, I’m still new with about 5 months experience. I have a custom class that is full of options for the program, and many other things. I use it to pass data to different functions as a single parameter. This idea works very well.
🌐
Reddit
reddit.com › r/python › measure the real size of any python object
r/Python on Reddit: Measure the Real Size of Any Python Object
July 21, 2016 -

TL;DR: Use this script to measure sizes of objects in Python. This works for iterables, dicts and subclasses of Python's built-in Object class.

import sys
def get_size(obj, seen=None):
    """Recursively finds size of objects"""
    size = sys.getsizeof(obj)
    if seen is None:
        seen = set()
    obj_id = id(obj)
    if obj_id in seen:
        return 0
    # Important mark as seen *before* entering recursion to gracefully handle
    # self-referential objects
    seen.add(obj_id)
    if isinstance(obj, dict):
        size += sum([get_size(v, seen) for v in obj.values()])
        size += sum([get_size(k, seen) for k in obj.keys()])
    elif hasattr(obj, '__dict__'):
        size += get_size(obj.__dict__, seen)
    elif hasattr(obj, '__iter__') and not isinstance(obj, (str, bytes, bytearray)):
        size += sum([get_size(i, seen) for i in obj])
    return size

If you want more, here's how I built it!. View the latest code here.

🌐
AskPython
askpython.com › home › variable’s memory size in python
Variable's memory size in Python - AskPython
April 29, 2023 - string = "ab" print("The size of a string of two characters is:",sys.getsizeof(string),"bytes.") OUTPUT The size of a string of two characters is: 51 bytes. Okay, a string of two characters takes up 51 bytes of memory space. So that means an empty string takes up 49 bytes of memory space, and for each character, 1 extra byte is required. A string is an object in Python.
🌐
TutorialsPoint
tutorialspoint.com › finding-how-much-memory-is-being-used-by-an-object-in-python
Finding how much memory is being used by an object in Python
August 23, 2023 - The function returns the size of the given object in bytes. Import the required sys module. Create a dictionary with various data types, such as strings, integers, floats, lists, and functions. Create a function that takes the integer n as an input and returns a list of integers ranging from 0 to n-1. Use sys.getsizeof() to find the size of the methods create_nmbr_list and my_dictn.
🌐
Medium
essyking.medium.com › quick-tip-do-you-know-how-much-memory-your-python-objects-use-e3f2a9f5be8d
Quick Tip: Do you Know How Much Memory Your Python Objects Use? | by Esther Vaati | Medium
February 9, 2022 - 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.
🌐
w3resource
w3resource.com › python-exercises › python-basic-exercise-79.php
Python: Get the size of an object in bytes - w3resource
May 17, 2025 - import sys # Import the sys module to use sys.getsizeof() # Define three strings and assign values to them str1 = "one" str2 = "four" str3 = "three" x = 0 y = 112 z = 122.56 # Print the size in bytes of each variable print("Size of ", str1, "=", str(sys.getsizeof(str1)) + " bytes") print("Size of ", str2, "=", str(sys.getsizeof(str2)) + " bytes") print("Size of ", str3, "=", str(sys.getsizeof(str3)) + " bytes") print("Size of", x, "=", str(sys.getsizeof(x)) + " bytes") print("Size of", y, "=", str(sys.getsizeof(y)) + " bytes") # Define a list and assign values to it L = [1, 2, 3, 'Red', 'Black
🌐
Delft Stack
delftstack.com › home › howto › python › python size of object
How to Determine the Size of an Object in Python | Delft Stack
March 4, 2025 - This tutorial discusses how to determine the size of an object in Python. Learn various methods, including sys.getsizeof(), pympler, and tracemalloc, to measure memory usage effectively. Optimize your Python code and manage memory better with our comprehensive guide.
🌐
Python Land
python.land › home › tips & tricks › check memory usage of your python objects
Check memory usage of your Python objects • Python Land Tips & Tricks
April 9, 2022 - 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) print(sys.getsizeof(mylist)) # 48Code language: Python (python) 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.