In Python, why is a tuple of integers taking up less space than single integers?

Here's an example with random integers:

a, b, c, d = 79412623, 56529819571, 10431, 30461
t = (79412623, 56529819571, 10431, 30461)

And their sizes:

import sys
sys.getsizeof(t) # 88
aa, bb, cc, dd = sys.getsizeof(a), sys.getsizeof(b), sys.getsizeof(c), sys.getsizeof(d)
sum([aa,bb,cc,dd]) # 96

Why does a tuple take up less space?

+3
source share
2 answers

The number returned sys.getsizeofdoes not include the size of the objects contained in the container.

>>> sys.getsizeof({1:2})
280
>>> sys.getsizeof({'a_really_long_string_that_takes_up_lots_of_space':'foo'})
280
+13
source

I am working on 32-bit Windows XP with Python 2.6.2 and I have tried your code that looks like this:

In [15]: a, b, c, d = 79412623, 56529819571, 10431, 30461

In [16]: t = (79412623, 56529819571, 10431, 30461)

In [17]: sys.getsizeof (t) Out [17]: 44

In [18]: aa, bb, cc, dd = sys.getsizeof (a), sys.getsizeof (b), sys.getsizeof (c), sys.getsizeof (d)

In [19]: sum ([aa, bb, cc, dd]) Out [19]: 56

+3
source

All Articles