Legitimate use of the "is" comparison operator?

Jean-Paul Calderone exarkun at divmod.com
Sat Jun 17 03:53:08 EDT 2006


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.
>
>Example:
>
>a = range(5)
>b = range(5)
>
>if len(a) is len(b):
>    print "They're the same size!"
>else:
>    print "They're not the same size!"
>

No, this is wrong.

>>> a = range(100)
>>> b = range(100)
>>> len(a) is len(b)
False

Use "is" to determine if two variables refer to exactly the same
object, never to determine if two objects are equal.

Jean-Paul



More information about the Python-list mailing list