is and ==

Alex Martelli aleaxit at yahoo.com
Mon Feb 26 17:27:22 CET 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:movk9t0una5nuca6upgk9rcco96fbkeu51 at 4ax.com...
> Just a quick question I hope as an equally quick (and easy) answer...
>
> Is there a functional difference between 'is' and '==' ?  If there is, I
can't
> find it.

There is a vast functional difference: 'is' verifies the
two operands refer to the SAME object (identity); '==' is
much more easily satisfied -- it compares the values of
the operands, and is true, not just for identity, but for
any equality.

For example:

>>> onelist = [1,2,3]
>>> another = [1,2,3]
>>> onelist is another
0
>>> onelist == another
1
>>> analias = onelist
>>> analias is onelist
1
>>> analias == onelist
1
>>>

If you care about whether onelist and another refer to the
SAME object, then 'is' is the right test; if you care
about whether the (possibly distinct) objects to which
they refer happen to have equal values right now (although
differing in identity), then '==' is the right test.

If 'is' returns true, then any alteration to the (one and
only) object referred to will be seen from any of the
references to it; '==' implies no such effect.

I.e., in the above example, if you do a onelist.append(4),
then you will also observe, e.g., len(analias) becomes 4,
but another remains completely unaffected, and the == test
has now become false (the two separate and distinct objects
that onelist and another refer to used to be of equal value,
but this becomes false if and when one is altered and the
other one is not).


Alex






More information about the Python-list mailing list