# sort the list

bonono at gmail.com bonono at gmail.com
Wed Nov 23 10:50:03 CET 2005

```Peter Otten wrote:
> bonono at gmail.com wrote:
>
> > Duncan Booth wrote:
> >> e.g. it is stable when you reverse the order:
> >>
> >> >>> lst = [[4,1],[4,2],[9,3],[5,4],[2,5]]
> >> >>> list(reversed([ x[-1] for x in sorted([ (x[0],x) for x in lst ]) ]))
> >> [[9, 3], [5, 4], [4, 2], [4, 1], [2, 5]]
> >> >>> l1 = list(lst)
> >> >>> l1.sort(key=operator.itemgetter(0), reverse=True)
> >> >>> l1
> >> [[9, 3], [5, 4], [4, 1], [4, 2], [2, 5]]
> >>
> > Just curious, which one is supposed to be the right answer ? and why
> > the second one is preferable over the first one(if both is right,
> > assume we only care about x[0]).
> >
> > Of course, there is no reason to DIY when the built-in can do the job.
>
> "Stability" means items with the same key preserve their relative position.
> In the original list of the example [4, 1] and [4, 2] both have the same
> key. Therefore [4, 1] should stay before [4, 2], so the second is the