on sorting things

Chris Angelico rosuav at gmail.com
Thu Dec 19 03:22:35 EST 2019


On Thu, Dec 19, 2019 at 6:36 PM Eli the Bearded <*@eli.users.panix.com> wrote:
>
> I recently saw a link to an old post on a blog and then started looking
> at the newer posts. This one:
>
> https://leancrew.com/all-this/2019/11/the-key-to-sorting-in-python/
>
> discusses ways to deal with useful sorting of movie / television show
> titles. Some initial words should be re-ordered for sorting purposes
> (_Adventures of Huckleberry Finn, The_), roman numbers should sort like
> regular numbers (_Rocky V_ comes before _Rocky IX_), and something needs
> to be done about sorting accented vowels.
>
> But what caught my eye most, as someone relatively new to Python but
> with long experience in C in Perl, is sorting doesn't take a
> *comparison* function, it takes a *key generator* function, and that
> function is supposed to transform the thing into something that the
> native comparison knows how to compare.
>
> This seems a strange choice, and I'm wondering if someone can explain
> the benefits of doing it that way to me.
>

If you provide a comparison function, it has to be called for every
pair that need to be compared. Plus, it usually has to be written such
that it does the same thing twice:

arrayInJavaScript.sort((x, y) => x.some_attr[0] > y.some_attr[0])

python_list.sort(key=lambda x: x.some_attr[0])

Thirdly, a key function can easily handle three-way comparisons,
whereas a comparison function usually just offers two-way - it's
harder to write a comparison function for -1, 0, 1 returns. So the
sort is much less likely to be stable.

ChrisA


More information about the Python-list mailing list