Sorting in reverse is not the same as sorting then reversing

Stefan Behnel stefan_ml at behnel.de
Fri Jun 5 10:50:15 EDT 2015


Steven D'Aprano schrieb am 05.06.2015 um 16:07:
> Sorting in reverse does not give the same result as sorting then reversing.
> 
> It's easiest to see with a key function:
> 
> py> a = ['fox', 'dog', 'DOG', 'cat', 'ape']
> py> b = a[:]
> py> a.sort(key=str.lower, reverse=True)
> py> b.sort(key=str.lower)
> py> b.reverse()
> py> a
> ['fox', 'dog', 'DOG', 'cat', 'ape']
> py> b
> ['fox', 'DOG', 'dog', 'cat', 'ape']
> 
> Sorting in reverse keeps the initial order of any equal elements unchanged.
> Sorting, then reversing, reverses them.
> 
> (Thanks to Tim Peters for the tip.)

... and for implementing this in the first place. :)

For those of you who didn't know and now got interested, the relevant term
here is "stable sorting". It means that elements that compare equal keep
their relative order. That's a general property of Python's sort algorithm.
All that "reverse=True" does is to change "lower than" into "greater than"
and vice versa for elements that compare unequal. It does not change the
behaviour for elements that compare equal, which means that they keep the
same relative order in both cases (reversed/non-reversed).

Stefan





More information about the Python-list mailing list