[Python-Dev] Re: Re: lists v. tuples (original) (raw)

Guido van Rossum guido@python.org
Sun, 16 Mar 2003 08:06:02 -0500


> Guido> Yes. And I'm still hoping to remove cmp; there should be > Guido> only one way to overload comparisons.

[Andrew]

> Moreover, for some data structures, the cmp approach can be > expensive. For example, if you're comparing sequences of any kind, > and you know that the comparison is for == or !=, you have your answer > immediately if the sequences differ in length. If you don't know > what's being tested, as you wouldn't inside cmp, you may spend a > lot more time to obtain a result that will be thrown away.

[Guido]

Yes. OTOH, as long as cmp() is in the language, these same situations are more efficiently done by a cmp implementation than by calling lt and then eq or similar (it's hard to decide which order is best). So cmp() should be removed at the same time as cmp.

I realized the first sentence wasn't very clear. I meant that implementing cmp() is inefficient without cmp for some types (especially container types). Example:

cmp(range(1000)+[1], range(1000)+[0])

If the list type implements cmp, each of the pairs of items is compared once. OTOH, if the list type only implemented lt, eq and gt, cmp() presumably would have to try one of those first, and then another one. If it picked lt followed by eq, it would get two False results in a row, meaning it could return 1 (cmp() doesn't really expect incomparable results :-), but at the cost of comparing each pair of items twice. If cmp() picked another set of two operators to try, I'd simply adjust the example.

--Guido van Rossum (home page: http://www.python.org/~guido/)