From some of the answers on Stackoverflow, I came to know that from -5 to 256 same memory location is referenced thus we get true for:
>>> a = 256
>>> a is 256
True
Now comes the twist (see this line before marking duplicate):
>>> a = 257
>>> a is 257
False
This is completely understood, but now if I do:
>>> a = 257; a is 257
True
>>> a = 12345; a is 12345
True
Why?
Generally speaking, numbers outside the range -5 to 256 will not necessarily have the optimization applied to numbers within that range. However, Python is free to apply other optimizations as appropriate. In your cause, you're seeing that the same literal value used multiple times on one line is stored in a single memory location no matter how many times it's used on that line. Here are some other examples of this behavior:
>>> s = 'a'; s is 'a'
True
>>> s = 'asdfghjklzxcvbnmsdhasjkdhskdja'; s is 'asdfghjklzxcvbnmsdhasjkdhskdja'
True
>>> x = 3.14159; x is 3.14159
True
>>> t = 'a' + 'b'; t is 'a' + 'b'
True
>>>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With