From this link I learnt that
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you actually just get back a reference to the existing object
But when I tried to give some example for my session and I found out that it behaves differently with assignment and tuple unpacking.
Here is the snippet:
>>> a,b = 300,300
>>> a is b
True
>>> c = 300
>>> d = 300
>>> c is d
False
Because int is immutable, Python may or may not use exists object, if you save the following code in to a script file, and run it, it will output two True.
a, b = 300, 300
print a is b
c = 300
d = 300
print c is d
When Python compile the code, it may reuse all the constants. Becasue you input your code in a python session, the codes are compiled line by line, Python can't reuse all the constants as one object.
The document only says that there will be only one instance for -5 to 256, but doesn't define the behavior of others. For immutable types, is
and is not
is not important, because you can't modify them.
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