Sorting in reverse is not the same as sorting then reversing

Peter Otten __peter__ at web.de
Fri Jun 5 10:59:50 EDT 2015


Steven D'Aprano wrote:

> 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.

If there were no reverse flag you could reverse, then sort, then reverse 
again.

> (Thanks to Tim Peters for the tip.)





More information about the Python-list mailing list