is and ==

Jay O'Connor joconnor at cybermesa.com
Mon Feb 26 11:59:34 EST 2001


Aahz Maruch wrote:

> In article <movk9t0una5nuca6upgk9rcco96fbkeu51 at 4ax.com>,
> Daniel Klein  <danielk at aracnet.com> wrote:
> >
> >Is there a functional difference between 'is' and '==' ?  If there is, I can't
> >find it.
>
> >>> a = 'xy'
> >>> b = a
> >>> c = 'x' + 'y'
> >>> d = 'xy'
> >>> a is b
> 1
> >>> a is d
> 1
> >>> a is c
> 0
> >>> a == c
> 1
>
> Essentially, is tests for object identity: are two variables pointing to
> the same location in memory.  == tests to see whether the *values* are
> equal.

Consider the following example

>>> class TestVal:
 def __init__(self):
  self.x = 100
 def __cmp__(self, other):
  return cmp (self.x, other.x)


>>> x = TestVal()
>>> y = TestVal()
>>> x == y
1
>>> x is y
0
>>> x =y
>>> x is y
1

x == y is true because I've defined what == means, a value comparison, but x is y
is false because they are not both the same object.  However by assign the variable
x to be y, I now get true for "x is y" because they are now the same object

Take care,
Jay





More information about the Python-list mailing list