In [39]: lis=["012345", "MYNAME" "Mon", "A", 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20] In [40]: k=[lis[:] for _ in xrange(80000)] In [41]: k.__sizeof__() Out[41]: 325664 In [42]: sys.getsizeof(k)
According to the code in sysmodule.c it looks like it is calling the __sizeof__ method to get the size of the object.
837 method = _PyObject_LookupSpecial(o, &PyId___sizeof__); 838 if (method == NULL) { 839 if (!PyErr_Occurred()) 840 PyErr_Format(PyExc_TypeError, 841 "Type %.100s doesn't define __sizeof__", 842 Py_TYPE(o)->tp_name); 843 } 844 else { 845 res = PyObject_CallFunctionObjArgs(method, NULL); 846 Py_DECREF(method); 847 }
and then adds some gc overhead to it:
860 861 if (PyObject_IS_GC(o)) { 862 PyObject *tmp = res; 863 res = PyNumber_Add(tmp, gc_head_size); 864 Py_DECREF(tmp); 865 } 866 return res; 867 }
We can also use recursive sizeof recipe , as suggested in docs , to recursively calculate the size of each container:
In [17]: total_size(k) #from recursive sizeof recipe Out[17]: 13125767 In [18]: sum(y.__sizeof__() for x in k for y in x) Out[18]: 34160000