'is' versus '=='

Alan Daniels danielsatalandanielsdotcom
Mon May 7 22:22:17 EDT 2001


On 07 May 2001 10:04:34 -0700, Humanity let out a collective sigh of
relief when Aaron Ginn <aaron.ginn at motorola.com> finally typed:

>Maybe I have an incorrect understanding of the 'is' operator, but I
>was under the impression that 'is' and '==' operated the same way.

Depending on how far you've gotten in learning Python so far, you may
or may not know this: Everything in Python is an object. EVERYTHING,
even the primitive types such as integers, floats, strings, etc.

With that in mind, you can think of 'is' as checking if two names
point to the same object, and '==' as checking if the CONTENTS of the
two objects are the same. The reason you want to be careful using 'is'
is that, for primitives, the results won't always be what you expect.
Note that 'a is b' is the same as asking if id(a) == id(b).

For example:

>>> # This returns zero since 123.45 is "created" twice,
... # thus giving you two different objects.
...
>>> x = 123.45
>>> y = 123.45
>>> x is y
0

>>> # Here we make sure x and y point to the same "object",
... # specifically the number 123.45.
...
>>> x = 123.45
>>> y = x
>>> x is y
1

See the difference? The reason this is tricky is because an item make
or may not already be created or reused behind the scenes for
performance reasons. As an example (if I recall correctly), the
integers 0 through 100 are pre-created since they're used in code
so often.

Hope-this-helps-rather-than-confuses'ly yours, Alan.

==============================
Alan Daniels
daniels at alandaniels dot com



More information about the Python-list mailing list