The size just refers to the outermost object and not the nested ones. From the perspective of getsizeof
the object size is just the size of the object plus the size of the pointers contained in the object not the objects being pointed to. You can see this from the following:
>>> import sys
>>> sys.getsizeof([])
64
>>> sys.getsizeof([[]])
72
>>> sys.getsizeof([[[]]])
72
>>> sys.getsizeof([[],[]])
80
>>> sys.getsizeof([[[]],[[]]])
80
If you want to get the total memory footprint you will either need to recursively find the sizes for the object or use some other memory profiling.
Also if you are writing your own objects and want getsizeof
to correctly return the size you can implement your own __sizeof__
method. For example:
import sys
class mylist:
def __init__(self, iterable):
self.data = list(iterable)
def __sizeof__(self):
return object.__sizeof__(self) + \
sum(sys.getsizeof(v) for v in self.__dict__.values()) + \
sum(sys.getsizeof(item) for item in self.data)
original_data = [[1,2,3], [1,2,3]]
print(sys.getsizeof(original_data))
foo = mylist(original_data)
print(sys.getsizeof(foo))
Results:
~/code_snippets$ python3 sizeof_list.py
80
336