The memory assigned is not disproportional; you are creating 100,000 objects! As you can see, they take up roughly 34 megabytes of space:

>>> sys.getsizeof(Test())+sys.getsizeof(Test().__dict__)
344
>>> (sys.getsizeof(Test())+sys.getsizeof(Test().__dict__)) * 1000000 / 10**6
34.4 #megabytes

You can get a minor improvement with __slots__, but you will still need about 20MB of memory to store those 100,000 objects.

>>> sys.getsizeof(Test2())+sys.getsizeof(Test2().__slots__)
200
>>> sys.getsizeof(Test2())+sys.getsizeof(Test2().__slots__) * 1000000 / 10**6
20.0 #megabytes

(With credit to mensi's answer, sys.getsizeof is not taking into account references. You can autocomplete to see most of the attributes of an object.)

See SO answer: Usage of __slots__? http://docs.python.org/release/2.5.2/ref/slots.html

To use __slots__:

class Test2():
    __slots__ = ['a','b','c','d','e']

    def __init__(self):
        ...
Answer from ninjagecko on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › size of python objects different? [real memory vs sys.getsizeof()]
r/learnpython on Reddit: Size of python objects different? [Real memory vs sys.getsizeof()]
November 11, 2016 -

Hi Pyople!

Yesterday I learned about sys.getsizeof() function and try some code. More specifically:

lst = [i for i in range(1000000000)]  # one mld numbers, creating for about a minute

When I use sys.getsizeof(lst), it returns: 8058558880. Which is correct. But when I look at my system resources in Linux Centos7 IPython (Python 3.4) I see: ipython Memory: 39592564 K Shared Mem: 5176 K - That's freaking 40GB.

I don't understand why, if a object is 8 GB in size, takes 40 KGB system memory. I tried it in list that had around 400 MB and system took 400 * 5 (approx) = 2 GB (approx)

Why is it taking 5-times more memory than it should? Or is the problem only because I tried it in iPython / Konsole? And in program it wouldn't be a problem?

🌐
Ned Batchelder
nedbatchelder.com › blog › 202002 › sysgetsizeof_is_not_what_you_want
sys.getsizeof is not what you want | Ned Batchelder
February 9, 2020 - All built-in objects will return correct results [...] But the fact is, sys.getsizeof is almost never what you want, for two reasons: it doesn’t count all the bytes, and it counts the wrong bytes.
🌐
Reddit
reddit.com › r/learnpython › why does a 9 gb list appear to use 40 gb of memory?
r/learnpython on Reddit: Why does a 9 GB list appear to use 40 GB of memory?
October 9, 2021 -

Can someone help me understand what's going on here? My OS reports that a python process whose only large object is a 9 GB list is consuming 40.6 GB of system memory. I repeated this test several times with both the interactive and standard interpreters and the results are pretty consistent.

import sys
import psutil

#memory in use prior to generating list
prior_used = psutil.virtual_memory().used

print(f"Prior used: {round(prior_used/1e9, 2)} GB")
z = [*range(1000000000)]
list_size = sys.getsizeof(z)
print(f"List size: {round(list_size/1e9, 2)} GB")

#memory in use after to generating list
post_used = psutil.virtual_memory().used
print(f"Post used: {round(post_used/1e9, 2)} GB")

difference = post_used - prior_used
print(f"Memory used by list: {round(difference/1e9, 2)} GB")

#clear the list
z = None
after_deleting = psutil.virtual_memory().used
print(f"Memory used after clearing the list: {round(after_deleting/1e9, 2)} GB")

# output:
# Prior used: 3.27 GB
# List size: 9.0 GB
# Post used: 43.87 GB
# Memory used by list: 40.6 GB
# Memory used after clearing the list: 3.28 GB
Top answer
1 of 2
11

I will attempt to answer your question from a broader point of view. You're referring to two functions and comparing their outputs. Let's take a look at their documentation first:

  • len():

Return the length (the number of items) of an object. The argument may be a sequence (such as a string, bytes, tuple, list, or range) or a collection (such as a dictionary, set, or frozen set).

So in case of string, you can expect len() to return the number of characters.

  • sys.getsizeof():

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.

So in case of string (as with many other objects) you can expect sys.getsizeof() the size of the object in bytes. There is no reason to think that it should be the same as the number of characters.

Let's have a look at some examples:

>>> first = "First"
>>> len(first)
5
>>> sys.getsizeof(first)
42

This example confirms that the size is not the same as the number of characters.

>>> second = "Second"
>>> len(second)
6
>>> sys.getsizeof(second)
43

We can notice that if we look at a string one character longer, its size is one byte bigger as well. We don't know if it's a coincidence or not though.

>>> together = first + second
>>> print(together)
FirstSecond
>>> len(together)
11

If we concatenate the two strings, their combined length is equal to the sum of their lengths, which makes sense.

>>> sys.getsizeof(together)
48

Contrary to what someone might expect though, the size of the combined string is not equal to the sum of their individual sizes. But it still seems to be the length plus something. In particular, something worth 37 bytes. Now you need to realize that it's 37 bytes in this particular case, using this particular Python implementation etc. You should not rely on that at all. Still, we can take a look why it's 37 bytes what they are (approximately) used for.

String objects are in CPython (probably the most widely used implementation of Python) implemented as PyStringObject. This is the C source code (I use the 2.7.9 version):

typedef struct {
    PyObject_VAR_HEAD
    long ob_shash;
    int ob_sstate;
    char ob_sval[1];

    /* Invariants:
     *     ob_sval contains space for 'ob_size+1' elements.
     *     ob_sval[ob_size] == 0.
     *     ob_shash is the hash of the string or -1 if not computed yet.
     *     ob_sstate != 0 iff the string object is in stringobject.c's
     *       'interned' dictionary; in this case the two references
     *       from 'interned' to this object are *not counted* in ob_refcnt.
     */
} PyStringObject;

You can see that there is something called PyObject_VAR_HEAD, one int, one long and a char array. The char array will always contain one more character to store the '\0' at the end of the string. This, along with the int, long and PyObject_VAR_HEAD take the additional 37 bytes. PyObject_VAR_HEAD is defined in another C source file and it refers to other implementation-specific stuff, you need to explore if you want to find out where exactly are the 37 bytes. Plus, the documentation mentions that sys.getsizeof()

adds an additional garbage collector overhead if the object is managed by the garbage collector.

Overall, you don't need to know what exactly takes the something (the 37 bytes here) but this answer should give you a certain idea why the numbers differ and where to find more information should you really need it.

2 of 2
2

To quote the documentation:

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.

Built in strings are not simple character sequences - they are full fledged objects, with garbage collection overhead, which probably explains the size discrepancy you're noticing.

🌐
Stack Abuse
stackabuse.com › bytes › determining-the-size-of-an-object-in-python
Determining the Size of an Object in Python
September 8, 2023 - Python provides a built-in function, sys.getsizeof(), which can be used to determine the size of an object.
🌐
GitHub
github.com › pandas-dev › pandas › issues › 11595
Optionally use sys.getsizeof in DataFrame.memory_usage · Issue #11595 · pandas-dev/pandas
November 13, 2015 - I would like to know how many bytes my dataframe takes up in memory. The standard way to do this is the memory_usage method df.memory_usage(index=True) For object dtype columns this measures 8 byte...
Author   mrocklin
Top answer
1 of 2
85

They are not the same thing at all.

len() queries for the number of items contained in a container. For a string that's the number of characters:

Return the length (the number of items) of an object. The argument may be a sequence (string, tuple or list) or a mapping (dictionary).

sys.getsizeof() on the other hand returns the memory size of the object:

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.

Python string objects are not simple sequences of characters, 1 byte per character.

Specifically, the sys.getsizeof() function includes the garbage collector overhead if any:

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

String objects do not need to be tracked (they cannot create circular references), but string objects do need more memory than just the bytes per character. In Python 2, __sizeof__ method returns (in C code):

Py_ssize_t res;
res = PyStringObject_SIZE + PyString_GET_SIZE(v) * Py_TYPE(v)->tp_itemsize;
return PyInt_FromSsize_t(res);

where PyStringObject_SIZE is the C struct header size for the type, PyString_GET_SIZE basically is the same as len() and Py_TYPE(v)->tp_itemsize is the per-character size. In Python 2.7, for byte strings, the size per character is 1, but it's PyStringObject_SIZE that is confusing you; on my Mac that size is 37 bytes:

>>> sys.getsizeof('')
37

For unicode strings the per-character size goes up to 2 or 4 (depending on compilation options). On Python 3.3 and newer, Unicode strings take up between 1 and 4 bytes per character, depending on the contents of the string.

For containers such as dictionaries or lists that reference other objects, the memory size given covers only the memory used by the container and the pointer values used to reference those other objects. There is no straightforward method of including the memory size of the ‘contained’ objects because those same objects could have many more references elsewhere and are not necessarily owned by a single container.

The documentation states it like this:

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

If you need to calculate the memory footprint of a container and anything referenced by that container you’ll have to use some method of traversing to those contained objects and get their size; the documentation points to a recursive recipe.

2 of 2
2

key difference is that len() will give actual length of elements in container , Whereas sys.getsizeof() will give it's memory size which it occupy

for more information read docs of python which is available at https://docs.python.org/3/library/sys.html#module-sys

🌐
datagy
datagy.io › home › python posts › how to get file size in python in bytes, kb, mb, and gb
How to Get File Size in Python in Bytes, KB, MB, and GB • datagy
November 4, 2022 - You first learned how to use the os library to explore two different methods of getting the size of a file. Then, you learned how to use the Python pathlib library to get the size of a file. Finally, you learned how to use these methods to convert the sizes of files to KB, MB, and GB.
Find elsewhere
🌐
GeeksforGeeks
geeksforgeeks.org › 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.
🌐
Medium
medium.com › shimakaze-soft-techblog › リスト内包表記とlistでは確保されているメモリサイズが違う-python-3-7-af3af1472075
リスト内包表記とlistでは確保されているメモリサイズが違う (Python 3.7) | by shimakaze_soft | shimakaze-soft-techblog | Medium
September 1, 2019 - sys.getsizeof()は、名前の通りオブジェクトのサイズを測る関数です。関数の引数にオブジェクトを渡すことで、Bite単位でサイズを返してくれます。
🌐
TutorialsPoint
tutorialspoint.com › difference-between-sizeof-and-getsizeof-method-in-python
Difference between __sizeof__() and getsizeof() method in Python
April 17, 2023 - The getsizeof() operator internally calls the __sizeof__() operator and adds an extra overhead while returning the size of the object for garbage collection. It returns 64 bytes(depending upon the system it can vary) for an empty list and 8 bytes for each list element.
🌐
CodeRivers
coderivers.org › blog › size-python
Understanding `sys.getsizeof()` in Python: A Deep Dive - CodeRivers
April 7, 2025 - In Python, understanding the memory size of objects is crucial, especially when dealing with large datasets or optimizing code for memory efficiency. The `sys.getsizeof()` function provides a way to determine the size of an object in bytes. This blog post will explore the fundamental concepts ...
🌐
Reddit
reddit.com › r/learnprogramming › [python 3.5] what does sys.getsizeof(object) show me exactly when i use this instruction?
r/learnprogramming on Reddit: [Python 3.5] What does sys.getsizeof(object) show me exactly when I use this instruction?
June 28, 2017 -

I was watching a numpy video on YouTube and the presenter made a point about numpy arrays versus python lists, and he did so in an odd manner. He was pointing out that one of the advantages of numpy array are how they take up less space, but when I tried to remake his demonstration in IDLE I didn’t get the same results.

import numpy as np
import sys

a = range(1000)
print('Information pertaining to a')
print('Get size', sys.getsizeof(a))
print('Type', type(a))
print('Print of actual a', a, '\n')

b = []
for i in range (1000):
    b.append(i)
print('Information pertaining to b')
print('Get size', sys.getsizeof(b))
print('Type', type(b))
print('Print of actual b', b, '\n')

c = np.arange(1000)
print('Information pertaining to c')
print('Get size', sys.getsizeof(c))
print('Type', type(c))
print('Print of actual c', c, '\n')

d = 5
print('Information pertaining to d')
print('Get size', sys.getsizeof(d))
print('Type', type(d))
print('Print of actual d', d, '\n')

e = 'e'
print('Information pertaining to e')
print('Get size', sys.getsizeof(e))
print('Type', type(e))
print('Print of actual e', e, '\n')

When I run this code, it shows me that the np array is indeed a bit lighter than the py list (9000 bytes vs 8000 bytes), but for some reason it doesn’t show me the full size of the range. It looks like he’s only showing me the space taken up by the letter 'a' (only 48 bytes). So I’m wondering, what exactly is getsizeof() meant to do? And why does it treat different kinds of list-like objects differently?

🌐
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
🌐
Envato Tuts+
code.tutsplus.com › home › python
Understand How Much Memory Your Python Objects Use | Envato Tuts+
May 20, 2022 - It just contains an 8-byte (on 64-bit versions of CPython) pointer to the actual int object. What that means is that the getsizeof() function doesn't return the actual memory of the list and all the objects it contains, but only the memory of ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › difference-between-__sizeof__-and-getsizeof-method-python
Difference between __sizeof__() and getsizeof() method - Python - GeeksforGeeks
July 12, 2025 - We have two Python methods, __sizeof__() and sys.getsizeof(), both used to measure the memory size of an object. While they seem similar, they produce different results. For example, calling these methods on the same object may return different values. Understanding this difference is essential for efficient memory management especially in ...
🌐
GeeksforGeeks
geeksforgeeks.org › find-the-size-of-a-list-python
Find the size of a list - Python - GeeksforGeeks
October 10, 2022 - import sys # sample lists list1 = [1, 2, 3, 5] list2 = ["GeeksForGeeks", "Data Structure", "Algorithms"] list3 = [1, "Geeks", 2, "For", 3, "Geeks"] # print the sizes of sample lists print("Size of list1: " + str(sys.getsizeof(list1)) + "bytes") print("Size of list2: " + str(sys.getsizeof(list2)) + "bytes") print("Size of list3: " + str(sys.getsizeof(list3)) + "bytes")
🌐
I-harness
code.i-harness.com › en › q › 10c28bc
mb gb - What is the difference between len() and sys.getsizeof() methods in python? - CODE Q&A Solved
See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents. However, in your case, there's a much simpler solution: sys.getsizeof(field) + sys.getsizeof(field[0]) will do.