Semantics of ==

Greg Ewing (using wmwd2zz02 at
Wed Mar 17 02:35:11 CET 2004

John Roth wrote:
>>  >>> l=[1]
>>  >>> s=l
>>  >>> l.append(s)
>>  >>> w=[1]
>>  >>> r=[1,w]
>>  >>> w.append(r)
>>  >>> s
>>  [1, [...]]
>>  >>> w
>>  [1, [1, [...]]]
>>  >>> s==w
>>  True

You've created two cyclic data structures. The ==
operator happens to regard them as equal, but they're
not identical, since they have different structures.
The first one is a list which refers directly to
itself, and the second contains another list which
refers back to the first list.

 >>  >>> s[0]=2
 >>  >>> w[0]=2
 >>  >>> s==w
 >>  False

If you print out s and w at this point:

 >>> s
[2, [...]]
 >>> w
[2, [1, [...]]]

They're now different in a way that == can see, so
it says they're not equal.

 > It appears as if two equal objects
 > can become unequal if you perform the same operations on them

Since the objects weren't really the same to begin with,
performing "the same operation" on them isn't entirely

By the way, it's not unusual for two objects that are not
identical to nevertheless compare ==, e.g.

 >>> 5 == 5.0

even though one is an integer and the other is a float.
Generally, == means that the *value* of two objects is
"equivalent" in some sense. What sense that is depends
on the types of the objects.

The == machinery for lists happens to include some
heuristics which attempt to make sense of cyclic
structures. As you've seen, however, the results can be
a bit confusing, and mightn't be what you want in some
cases. Probably it's best to avoid applying == to cyclic
structures if you can.

Greg Ewing, Computer Science Dept,
University of Canterbury,	
Christchurch, New Zealand

More information about the Python-list mailing list