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.

Answer from Martijn Pieters on Stack Overflow
🌐
Python
docs.python.org › 3 › library › sys.html
sys — System-specific parameters and functions
getsizeof() calls the object’s __sizeof__ method and adds an additional garbage collector overhead if the object is managed by the garbage collector.
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

Discussions

Size of python objects different? [Real memory vs sys.getsizeof()]

sys.getsizeof gives you the amount of memory allocated to the list itself, but you also have 10...00 int objects that the list only contains a pointer to.

More on reddit.com
🌐 r/learnpython
6
4
November 11, 2016
Strange behavior of sys.getsizeof
Hi! I expected that sys,getsizeof would return the same results in the following two scripts, but it returns different results. Why? Script 1 import sys a = [] a += [0] print(a) print(sys.getsizeof(a)) Output of script1 [0] 72 Script 2 import sys a = [] a.append(0) print(a) print(sys.getsizeof(a)) ... More on discuss.python.org
🌐 discuss.python.org
0
1
April 29, 2025
BUG: Incorrect results from `sys.getsizeof()` for multi-dimensional arrays
Describe the issue: While sys.getsizeof() seems to work correctly for one-dimensional arrays, it gives, in my opinion, incorrect results for multi-dimensional arrays. import sys import numpy as np ... More on github.com
🌐 github.com
2
January 2, 2022
[Python 3.5] What does sys.getsizeof(object) show me exactly when I use this instruction?
According to the docs, getsizeof is implementation-specific - it calls an object's __sizeof__ method on the object to retrieve this data. It might not be accurate for non-builtins. Edit: Here's an example: from collections import UserList import sys class MyList(UserList): def __sizeof__(self): return 100000000 class MyList2(UserList): pass my_new_list = MyList(range(100)) my_second_list = MyList2(range(100)) my_regular_list = list(range(100)) print("size of my_new_list:", sys.getsizeof(my_new_list)) # 100000024 print("size of my_second_list:", sys.getsizeof(my_second_list)) #56 print("size of my_regular_list:", sys.getsizeof(my_regular_list)) # 1008 Notice there's a bit of overhead that is also calculated. More on reddit.com
🌐 r/learnprogramming
9
1
June 28, 2017
🌐
GeeksforGeeks
geeksforgeeks.org › python › difference-between-__sizeof__-and-getsizeof-method-python
Difference between __sizeof__() and getsizeof() method - Python - GeeksforGeeks
July 12, 2025 - sys.getsizeof(): Use this when you need to assess the total memory usage of an object in a live program. It’s great for tasks like profiling a script handling large datasets or debugging why your application is consuming more RAM than expected.
🌐
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?

🌐
Python.org
discuss.python.org › python help
Strange behavior of sys.getsizeof - Python Help - Discussions on Python.org
April 29, 2025 - Hi! I expected that sys,getsizeof would return the same results in the following two scripts, but it returns different results. Why? Script 1 import sys a = [] a += [0] print(a) print(sys.getsizeof(a)) Output of script1 [0] 72 Script 2 import sys a = [] a.append(0) print(a) print(sys.getsizeof(a)) ...
🌐
Ned Batchelder
nedbatchelder.com › blog › 202002 › sysgetsizeof_is_not_what_you_want
sys.getsizeof is not what you want | Ned Batchelder
February 9, 2020 - I don’t know why those numbers are the way they are. PEP 393 has the details if you are curious. The point here is: sys.getsizeof is almost certainly not the thing you want. The “size” of a thing depends on how the thing is being represented. The in-memory Python data structures are one representation.
🌐
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.
Find elsewhere
🌐
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.
🌐
YouTube
youtube.com › python basics
Python Basics Sys Getsizeof Method - YouTube
Learn how to use the getsizeof method from the sys module for python programming. Getsizeof returns the number of bytes of an object for python programming t...
Published   November 3, 2018
Views   276
🌐
GitHub
github.com › numpy › numpy › issues › 20707
BUG: Incorrect results from `sys.getsizeof()` for multi-dimensional arrays · Issue #20707 · numpy/numpy
January 2, 2022 - obj_sizes = set() count = 0 size = 10_000 for name, obj in vars(np).items(): if type(obj) is type and np.number in obj.mro(): arr = np.arange(size, dtype=obj).reshape(100, 100) diff = sys.getsizeof(arr) - arr.nbytes obj_sizes.add(diff) count += 1 print(f'found sizes: {obj_sizes} for {count} dtypes') found sizes: {-9880, -19880, -319880, -159880, -79880, -39880} for 52 dtypes · import sys import numpy as np a = np.arange(10).reshape(2, 5) print('Array:') print(a) print('Bytes as reported by NumPy:', a.nbytes) print('Size as Python sees it:', sys.getsizeof(a)) print('The number of bytes is the
Author   pya
🌐
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?

🌐
Tutorialspoint
tutorialspoint.com › python › python_sys_getsizeof_method.htm
Python sys.getsizeof() method
The Python sys.getsizeof() method returns the size, in bytes of a Python object. This includes the object's contents and overhead. It is primarily used for memory profiling and debugging to understand how much memory an object consumes.
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.

🌐
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.
🌐
Codedamn
codedamn.com › news › python
How to Determine the Size of Objects in Python
July 2, 2023 - Python provides a built-in module named 'sys' which has a method called 'getsizeof()' that can be used to get the size of an object.
🌐
KooR.fr
koor.fr › Python › API › python › sys › getsizeof.wp
KooR.fr - Fonction getsizeof - module sys - Description de quelques librairies Python
RAG (Retrieval-Augmented Generation)et Fine Tuning d'un LLM Voir le programme détaillé Module « sys » Python 3.13.2 · getsizeof(object [, default]) -> int Return the size of object in bytes.
🌐
Read the Docs
stackless.readthedocs.io › en › 3.6-slp › library › sys.html
29.1. sys — System-specific parameters and functions — Stackless-Python 3.6.13 documentation
Return the current value of the recursion limit, the maximum depth of the Python interpreter stack. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. It can be set by setrecursionlimit(). sys.getsizeof(object[, default])¶ ·
🌐
GoShippo
goshippo.com › blog › measure-real-size-any-python-object
How to Measure the Real Size of Any Object in Python
April 14, 2025 - When you measure a size of an object, ... etc. sys.getsizeof only gives you the size of the object and their attributes, however it does not recursively add the size of sub-attributes. So I decided to fill in the gap. I wrote the helper below to recursively measure the size of a Python object (or ...
🌐
Readthedocs
sizeof.readthedocs.io › en › 0.6.0 › _source › sizeof.html
sizeof module — sizeof 0.6.0 documentation - Read the Docs
Estimate the memory consumption of a Python object (either the root object itself exclusively or, in the case of a deep traversal, the entire tree of objects reachable from it). >>> sys.getsizeof([]) == sizeof([]) True >>> sys.getsizeof(123) == sizeof(123) True >>> sys.getsizeof(123.0123) == ...