[Tutor] Why does CPython cache small integers "asymmetrically"?
boB Stepp
robertvstepp at gmail.com
Wed May 26 21:49:39 EDT 2021
I often wonder how Python design decisions are reached. I wish there
was a single go-to place for these sorts of questions!
I cannot resist asking why -- if anyone happens to know -- more
positive integers are cached than negative ones:
Python 3.9.5 (tags/v3.9.5:0a7dcbd, May 3 2021, 17:27:52) [MSC v.1928
64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> x = 256
>>> y = 256
>>> id(x)
1176492272016
>>> id(y)
1176492272016
>>> x = 257
>>> y = 257
>>> id(x)
1176503075504
>>> id(y)
1176503075408 # So Python stops caching at 2**16 on the positive side.
>>> x = -4
>>> y = -4
>>> id(x)
1176492075152
>>> id(y)
1176492075152
>>> x = -5
>>> x = -5
>>> id(x)
1176492075120
>>> id(y)
1176492075152 # But strangely (to me) stops at -2**2 on the negative side.
>>> x = 0
>>> y = 0
>>> id(x)
1176492075280 # Just to check. ~(:>))
I suppose most people tend to stick with whole numbers. But
nonetheless I find this a bit surprising that the negative numbers are
second class in this regard!
Cheers!
boB
More information about the Tutor
mailing list