The getizeof function does not measure the size of elements in a container, like a list. You need to add all the individual elements.
Here is the recipe for this.
Reproduced here:
from __future__ import print_function from sys import getsizeof, stderr from itertools import chain from collections import deque try: from reprlib import repr except ImportError: pass def total_size(o, handlers={}, verbose=False): """ Returns the approximate memory footprint an object and all of its contents. Automatically finds the contents of the following builtin containers and their subclasses: tuple, list, deque, dict, set and frozenset. To search other containers, add handlers to iterate over their contents: handlers = {SomeContainerClass: iter, OtherContainerClass: OtherContainerClass.get_elements} """ dict_handler = lambda d: chain.from_iterable(d.items()) all_handlers = {tuple: iter, list: iter, deque: iter, dict: dict_handler, set: iter, frozenset: iter, } all_handlers.update(handlers)
If you use this recipe and run it in the list, you can see the difference:
>>> alist=[[2**99]*10, 'a string', {'one':1}] >>> print('getsizeof: {}, total_size: {}'.format(getsizeof(alist), total_size(alist))) getsizeof: 96, total_size: 721
source share