Consider the following code:
x = 50000000
y = 50000000
print(hex(id(x)), hex(id(y)))
print(x is y)
This gives:
0x23ef28ec930 0x23ef28ec930
True
Now I was lead to believe that for small values python uses optimisation to cache these in memory. But it the number is quite clearly larger than this value which I believe is 256.
Why is it not when I declare these they are stored separately in memory?
Further to this if I add in the line y+=1
just before the print statement then x and y
are stored in separate locations in memory and x is y
is False
. I would have thought that as the are both the same object in memory that incrementing y
would increment x
also.
Clearly I am missing something fundamental and would appreciate it being cleared up.
As a further point does this behaviour depend on the variable type? What about if x,y
are not ints but lists, strings or any other object?
Thanks!