Reputation: 87
interactive terminal results:
In [11]: a=1111111111111111111111111111111111111111111111111111
In [12]: b=1111111111111111111111111111111111111111111111111111
In [13]: a is b
Out[13]: False
script results:
# overflow in ~ [13:55:16]
» python -c "a=1111111111111111111111111111111111111111111111111111;b=1111111111111111111111111111111111111111111111111111; print a is b"
True
Emmmmm. I think the result should be False... Because 1111111111111111111111111111111111111111111111111111
is much larger than 256
I know is
is not an equality test. But, when Python declares a variable(immutable type), like b = 1
, it will find out whether the object has been declared in the old object(a = 1
). If the object is declared(a = 1
), the variable will point directly to the old object and will not apply for new memory space.(a is b
is True
)
In [2]: a=1
In [3]: b=1
In [4]: a is b
Out[4]: True
emmmm. right?
As for “is” operator behaves unexpectedly with integers. It explains the usage of is
, but I still don't understand why these two methods lead to different results. :(
Maybe, it just depends on the Python implementation and runtime environment.
Upvotes: 2
Views: 123
Reputation: 2407
This is interesting.
Python 3.7.1 (default, Oct 22 2018, 11:21:55)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.1.1 -- An enhanced Interactive Python. Type '?' for help.
In [1]: a=1111111111111111111111111111111111111111111111111111
In [2]: b=1111111111111111111111111111111111111111111111111111
In [3]: id(a),id(b)
Out[3]: (139945897647488, 139945897647536)
In [4]: len(str(a))
Out[4]: 52
Upvotes: 0
Reputation: 5464
It really depends on what you are looking for. Use is
is for identity testing and ==
for equality testing. Do not rely on is
to check for equality.
Equality refers to the value of the object while identity refers to the pointer to the same object id. For example, if you run this in your terminal, is
will return False
:
a = 1111
b = int('1111')
print(a == b)
>>True
print(a is b)
>>False
The assumption to use is
not for identity test is not recommended and its behaviour depends on the Python implementation and runtime environment. I somehow also suspect because of how Python read your integers where they are repeated. For a further example:
a = 257
b = 257
a is b
>>False
From the docs:
Return value: New reference. Create a new integer object with a value of ival.
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. So it should be possible to change the value of 1. I suspect the behaviour of Python in this case is undefined. :-)
For optimization, short integers actually just refer back to the same object, this should also apply if you changed a single number in your value (non-repeated) above 256
, it will return False
.
Upvotes: 1