sort order for strings of digits

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Nov 1 20:27:15 EDT 2012


On Thu, 01 Nov 2012 11:53:06 +1100, Chris Angelico wrote:

> On Thu, Nov 1, 2012 at 10:44 AM, Steven D'Aprano
> <steve+comp.lang.python at pearwood.info> wrote:
>> On the contrary. If you are using cmp with sort, your sorts are slow,
>> and you should upgrade to using a key function as soon as possible.
>>
>>
> But cmp_to_key doesn't actually improve anything. So I'm not sure how
> Py3 has achieved anything; Py2 supported key-based sorting already.

Yes, but there is a lot of old code pre-dating key-based sorts. There's 
also some examples of code where it isn't obvious how to write it as a 
key-based sort, but a comparison function is simple. And people coming 
from other languages that only support comparison-based sorts (C?) will 
probably continue with what they know.

Even though key-based sorting is better, there's a lot of comparison 
sorting that falls under "if it ain't broke, don't fix it".

So even though key-based sorts are better, there are still comparison-
based sorts in the wild. Python 2 has to support them. Python 3, which is 
allowed to break backwards compatibility, does not. So when porting to 3, 
you have to change the sorts.

Most of the time it is simple to convert a comparison-based sort to a key-
based sort. For the cases where you either can't come up with a good key 
function yourself, or were you want to do so mechanically, Python 
provides cmp_to_key.


-- 
Steven



More information about the Python-list mailing list