Semantics of ==
Erik Max Francis
max at alcyone.com
Tue Mar 16 19:58:08 EST 2004
Axel Boldt wrote:
> Still trying to understand "=="... It appears as if two equal objects
> can become unequal if you perform the same operations on them:
>
> >>> l=[1]
> >>> s=l
> >>> l.append(s)
> >>> w=[1]
> >>> r=[1,w]
> >>> w.append(r)
> >>> s
> [1, [...]]
> >>> w
> [1, [1, [...]]]
> >>> s==w
> True
You're creating recursive lists (which is extremely rare in the real
world; I've never seen anyone create a self-referencing list in
real-life code. Tree structures and even recursive data structures are
one thing, but you're considering a very weird corner case here.
> Note that they're equal, yet are printed differently.
That's fine. 1 and 1.0 are printed differently (and even are of
different types) but they're equal. If you try running through the
element-wise algorithm that Python uses to determine equality of lists,
you'll see that they are in fact equal at this point. The first element
is 1, the second element is a list whose first element is 1, the second
element of that list is a list whose first element is 1, ad infinitum.
> >>> s[0]=2
> >>> w[0]=2
> >>> s==w
> False
>
> All of a sudden they have become unequal.
Because now they really are not equal. Show them:
>>> s
[2, [...]]
>>> w
[2, [1, [...]]]
The [...] doesn't indicate which sublist is recursively contained, so
you have to dig deeper:
>>> s[1]
[2, [...]]
>>> w[1][1]
[2, [1, [...]]]
So s is
[2, [2, [2, [2, ...]]]]
but w is
[2, [1, [2, [1, ...]]]]
Despite both recursing, it's clear that these lists are not element-wise
equal, and so Python is completely right in saying they're not.
Again, though, real-world creation of self-referencing lists is
extremely rare at best.
--
__ Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
/ \ San Jose, CA, USA && 37 20 N 121 53 W && &tSftDotIotE
\__/ Here day fights with night.
-- (the last words of Victor Hugo)
More information about the Python-list
mailing list