Semantics of ==

Erik Max Francis max at alcyone.com
Wed Mar 17 02:02:03 CET 2004


John Roth wrote:
> 
> "Axel Boldt" <axelboldt at yahoo.com> wrote in message
> news:40200384.0403161538.7407d9e2 at posting.google.com...
> > 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
> >
> > Note that they're equal, yet are printed differently.
> >
> >   >>> s[0]=2
> >   >>> w[0]=2
> >   >>> s==w
> >   False
> >
> > All of a sudden they have become unequal.
> >
> > Axel
> 
> You've got a recursive structure! I originally thought
> that the [...] was something you'd done to the printout,
> but it isn't.
> 
> I think the original True is a bug. It's getting confused
> by the recursion.

Nah, Python's completely right here.

That the original s and w have extra finite elements doesn't make them
unequal.  Follow Python's elementwise equality algorithm down and you'll
see they must be equal.  The original s is

>>> l = [1]
>>> s = l
>>> l.append(s)
>>> s
[1, [...]]

so it is

	[1, [1, [1, [1, [1, ...]]]]]

The original w is

>>> w = [1]
>>> r = [1, w]
>>> w.append(r)
>>> w
[1, [1, [...]]]

so it is also

	[1, [1, [1, [1, [1, ...]]]]]

The real weirdness you reach is when the recursive sublists are not
appended, but prepended:

>>> a = [1]
>>> a.insert(0, a)
>>> a
[[...], 1]

Here you could never even resolve a first element for comparison!

-- 
 __ 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