Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #92155

Re: Sorting in reverse is not the same as sorting then reversing

From Stefan Behnel <stefan_ml@behnel.de>
Subject Re: Sorting in reverse is not the same as sorting then reversing
Date 2015-06-05 16:50 +0200
References <5571ad0c$0$13005$c3e8da3$5496439d@news.astraweb.com>
Newsgroups comp.lang.python
Message-ID <mailman.202.1433515834.13271.python-list@python.org> (permalink)

Show all headers | View raw


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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Sorting in reverse is not the same as sorting then reversing Steven D'Aprano <steve@pearwood.info> - 2015-06-06 00:07 +1000
  Re: Sorting in reverse is not the same as sorting then reversing Stefan Behnel <stefan_ml@behnel.de> - 2015-06-05 16:50 +0200
  Re: Sorting in reverse is not the same as sorting then reversing Peter Otten <__peter__@web.de> - 2015-06-05 16:59 +0200
  Re: Sorting in reverse is not the same as sorting then reversing Skip Montanaro <skip.montanaro@gmail.com> - 2015-06-05 10:28 -0500

csiph-web