Legitimate use of the "is" comparison operator?
gherron at islandtraining.com
Sat Jun 17 10:18:23 CEST 2006
Jean-Paul Calderone wrote:
> On 17 Jun 2006 00:49:51 -0700, Mike Duffy <mike.s.duffy at gmail.com> wrote:
>> I just recently realized that the comparison operator "is" actually
>> works for comparing numeric values. Now, I know that its intended use
>> is for testing object identity, but I have used it for a few other
>> things, such as type checking, and I was just wondering whether or not
>> it is considered bad practice in the Python Community to use it for
>> numerics as well.
>> a = range(5)
>> b = range(5)
>> if len(a) is len(b):
>> print "They're the same size!"
>> print "They're not the same size!"
> No, this is wrong.
An even simpler demo of why this DEAD WRONG:
>>> 100 is (99+1)
This is asking if two different ways of computing the value (of 100) are
stored internally as one object with that value or two separate objects
each with that value.
But, lest you think you understand that, consider also:
>>> 2 is (1+1)
>>> 100 is 100
This is highly implementation dependent. The current (C) implementation
of Python has a cache for small integers, so the attempt to compare
values with "is" works for some small integers, and fails for some large
integers, but curiously, not all instances of comparing large integers.
>>>> a = range(100)
>>>> b = range(100)
>>>> len(a) is len(b)
> Use "is" to determine if two variables refer to exactly the same
> object, never to determine if two objects are equal.
More information about the Python-list