Q: sort's key and cmp parameters

Paul Rubin http
Thu Oct 1 19:19:05 EDT 2009


Raymond Hettinger <python at rcn.com> writes:
> If you're assuming a consistent sort-order (transitivity, not
> evolving over time, etc), then the cmp method and key method
> are mathematically equivalent (you could always do a compare
> sort first, record the order produced, and assign the position
> number as a key function)

But that is an efficiency hit.

> If you're starting point is a cmp function (for instance,
> asking a dating service member whether they prefer
> mate x to mate y), then having to convert to a key function
> can be inconvenient.

Well, the issue there is that the comparison function may not be
transitive.  Maybe you really want a topological sort for that.

> All that being said, for many everyday uses, a key function is
> simpler to write and faster to run than a cmp function approach.

I still have never understood why cmp was removed.  Sure, key is more
convenient a lot (or maybe most) of the time, but it's not always.



More information about the Python-list mailing list