Question about sorted in Python 3.0rc1

Hrvoje Niksic hniksic at
Mon Sep 22 15:29:53 CEST 2008

josh logan <dear.jay.logan at> writes:

> sorted(P) # throws TypeError: unorderable types Player() < Player()
> The sorted function works when I define __lt__.
> I must be misreading the documentation, because I read for the
> documentation __cmp__ that it is called if none of the other rich
> comparison functions are defined.
> Is this a bug in Python 3.0rc1, or am I missing something?

What documentation are you referring to, exactly?  The whole __cmp__
thing was supposed to be removed from Python 3, so mention of it
sounds like a documentation bug.

> Secondly, say that we suddenly need another sorting order, where we
> want to sort by decreasing score and then by DECREASING last name
> (instead of increasing last name, defined above). Now that the
> comparison function argument is taken away from the sorted builtin,
> how do we accomplish this with the "key" parameter?

By calling sort twice on the sequence:

lst.sort(key=lambda x: x.score)
lst.sort(key=lambda x: x.last_name, reverse=True)

As much as I like the key argument, I believe it was a mistake to
remove cmp, simply because it was the more general mechanism.
Emulating cmp with key is possible, but it requires creating a bunch
of objects for each sort.  (I'm aware that list.sort caches the
calculated keys, but it still has to create as many of them as there
are list items.)

More information about the Python-list mailing list