Are there any list comparison optimizations in Python?

Skip Montanaro skip at pobox.com
Fri Nov 16 09:35:40 CET 2001


    Huaiyu> So my question really is this: Is there any major practical use
    Huaiyu> for an object to be unequal to itself?  Would it be better to
    Huaiyu> just define (a==b) to take a shortcut of (a is b), always?

The "is" operator is defined to just do pointer comparisons.  Here are just
three different ways to generate objects that are equal but not "is":

>>> a = 457
>>> b = 99+358
>>> a is b
0
>>> a == b
1

>>> a = "now is the time..."
>>> b = " ".join(a.split())
>>> a is b
0
>>> a == b
1

>>> a = [1]
>>> b = [1]
>>> a == b
1
>>> a is b
0

In the first two cases perhaps Python could make sure that a and b shared
references to the same object, but I think that would require the
interpreter to do a lot more work just to maintain that consistency.

In the last case you most definitely don't want "is" and "==" to be
synonyms.  That would imply that a and b referred to the same object.  If
they did, any list-modifying methods applied using one name would be
reflected when that object was viewed using the other name, which is
generally not what you want for mutable objects.

-- 
Skip Montanaro (skip at pobox.com - http://www.mojam.com/)
It's only a 25% solution to our problems.  Of course, we only want to solve
25% of our problems, so it becomes a 100% solution.




More information about the Python-list mailing list