is and ==

Ben Hutchings ben.hutchings at roundpoint.com
Mon Feb 26 21:19:56 EST 2001


Steve Purcell <stephen_purcell at yahoo.com> writes:

> Daniel Klein wrote:
> > Is there a functional difference between 'is' and '==' ?  If there is,
> > I can't find it.
> 
> There is indeed a difference.
> 
> 'is' is an identity test, and '==' is an equality test:
<snip>
> Integers are both equal *and* identical:
> 
> >>> a = 1
> >>> b = 1
> >>> a is b
> 1
> >>> a == b
> 1

but only if they're small integers (the above doesn't work for 1000,
for instance).

What 'is' does is to test whether two names refer to the same object.
For objects of mutable types (such as lists and class types), this
may be important:

>>> a = [1]
>>> b = a
>>> a == b
1
>>> a is b
1
>>> a.append(2)
>>> b
[1, 2]

Here, b refers to the same list as a, so not only are they equal but a
change made through a is also visible through b.

>>> a = [1]
>>> b = [1]
>>> a == b
1
>>> a is b
0
>>> a.append(2)
>>> b
[1]

Here, a and b initially refer to identical (that is, equal) lists, but
they are separate lists so a change made through a is not visible
through b.

With immutable types, obviously, there's no issue of changes being
visible through another name, so Python can safely conserve memory by
eliminating duplicate objects.  I think this currently only happens
with small integers and string literals.  For the same reason, I'm not
sure that it's at all useful to test whether two names referring to
immutable objects actually refer to the same object.

-- 
Any opinions expressed are my own and not necessarily those of Roundpoint.



More information about the Python-list mailing list