An oddity in list comparison and element assignment

michael.f.ellis at gmail.com michael.f.ellis at gmail.com
Thu Jun 1 13:44:58 EDT 2006


Hi Tim,
In your example, a & b are references to the same object.  I agree they
should compare equally.  But please note that a==b is True at every
point in your example, even after the ValueError raised by b.remove(1).
 That's good consistent behavior.

My original example is a little different.  a and b never referred to
the same object.  They were containers created by different expressions
with no object in common.  The problem arises because the overloaded *
operator makes row level copies of the lists in b.  There's nothing
wrong with that, but the fact remains that a and b are different in a
very significant way.

I agree with Alex that checking for this type of inequality is not a
trivial programming exercise.  It requires (at least) a parallel
recursion that counts references with the containers being compared .
At the same time, I know that much harder programming problems have
been solved.  Where I disagree with Alex is in the labeling of the
existing behavior as 'natural'.

Alternatively, it might make sense to disallow == for containers by
raising a TypeError although that would eliminate a largely useful
feature.

Realistically, I know that Python is unlikely to adopt either
alternative.  It would probably break a lot of existing code.   My
point in the original post was to raise what I felt was a useful topic
for discussion and to help others avoid a pitfall that cost me a couple
of hours of head-scratching.

By the way, I've been programming professionally for over 25 years and
have used at least 30 different languages.  During the past few years,
Python has become my language of choice for almost everything because
it helps me deliver more productivity and value to my clients.

Cheers,
Mike


Tim Peters wrote:
> Think about a simpler case:
>
>     a = [1]
>     b = a
>     assert(a == b)
>     a.remove(1)
>     b.remove(1)
>
> Oops.  The last line dies with an exception, despite that a==b at the
> third statement and that ".remove(1)" is applied to both a and b.




More information about the Python-list mailing list