1

I have a question about space in the memory used by list and dict objects. My Python 3.7 shell shows:

>>> import sys
>>> list_ = []
>>> sys.getsizeof(list_)
64
>>> dict_ = {}
>>> sys.getsizeof(dict_)
240
>>> list_ += dict_,
>>> list_
[{}]
>>> sys.getsizeof(list_)
96

I don't understand what is going on.

  • The list object takes 64 bytes of memory (what's shown in shell) + 8 bytes for each element.
  • The dict object takes 240 bytes of memory.

  • So, after adding the dictionary as an element, the list should take 64 + 8 + 240 = 312 bytes.

Why did the memory taken by the list increase by only 32 bytes? What happened to the dict's 240 bytes memory? And why did the amount of memory used increase by just 32 bytes?

Brian61354270
  • 8,690
  • 4
  • 21
  • 43
Marco
  • 81
  • 3
  • 7

1 Answers1

1

Like @Kaya3 the size of the list does not include the size of the things it references.

>>> list_ = [{}]
>>> sys.getsizeof(list_)
40
>>> sys.getsizeof(list_[0])
136 
kpie
  • 9,588
  • 5
  • 28
  • 50
  • Thank You kpie and @kaya3. Now i understand. But one more question. Is there any quick way to check all memory used by the list and objects referenced by the list? – Marco Mar 08 '20 at 01:16
  • Well you could write a little recursive function that digs down into the list but there could be an issue if you have a reference to the list in the list or duplicates of the same reference. – kpie Mar 08 '20 at 01:18
  • You could examine the total memory used by your process before and after instantiating the list. https://stackoverflow.com/questions/938733/total-memory-used-by-python-process – kpie Mar 08 '20 at 01:20
  • thx for your help – Marco Mar 08 '20 at 01:23
  • @Marco did you [check the docs](https://docs.python.org/3/library/sys.html#sys.getsizeof)? There is a link to a [recipe](https://code.activestate.com/recipes/577504/) for just this. – juanpa.arrivillaga Mar 08 '20 at 02:00