I have been checking the function sys.getsizeof
, and I know that this returns the size in bytes of the parameter that is being passed.
I have some experience with C in which I can figure out the size of some values knowing the size of certain types. I have run some experiments with this function.
Note: I am using Python 3.7.3 on macOS to run the following:
For numbers
>>> sys.getsizeof(0)
24
>>> sys.getsizeof(1)
28
>>> sys.getsizeof(-1)
28
>>> sys.getsizeof(1.0)
24
>>> sys.getsizeof(-1.0)
24
For lists
>>> sys.getsizeof([])
64
>>> sys.getsizeof([1])
72
>>> sys.getsizeof([1.0])
72
>>> sys.getsizeof([0, 1])
80
For strings
>>> sys.getsizeof('d')
50
>>> sys.getsizeof('do')
51
For dictionaries
>>> sys.getsizeof({})
240
>>> sys.getsizeof({'a': 1})
240
>>> sys.getsizeof({'a': 1, 'b': 2})
240
>>> sys.getsizeof({'a': 1, 'b': 2, 'c': 3, 'd': 4})
240
I don't understand why the size of 0 is less than other integers. Even though I can figure out a pattern when adding more elements to a list or a string, but I don't understand why the size of the dictionary is the same no matter of the number key-value pairs it has.