sort by last then by first

Peter Abel p-abel at
Thu Jan 30 00:41:48 CET 2003

Alex Martelli <aleax at> wrote in message news:<X7RZ9.100045$0v.2892758 at>...
> Peter Abel wrote:
>    ...
> > If you change the order of sorting from
> > low order key to high order key, I can't see
> > any reason, why this shouldn't work stable.
> the list.sort method is NOT guaranteed to be stable.
> It generally LOOKS stable, for small enough lists,
> up to Python 2.2 -- and it has been changed to one
> that happens to be stable in 2.3 -- but it's never
> a good idea to rely on such things, which may well
> change from one version to another: list.sort at any
> time will be the fastest sort Tim Peters can think
> up, whether that's a stable one or not.
> If you DO need a stable sort, see:
> > # 1) Sort by 3rd name
> >>>> l.sort(lambda a,b:cmp(a[2],b[2]))
>  # 2) Sort by 2nd name
> >>>> l.sort(lambda a,b:cmp(a[1],b[1]))
>  # 3) Sort by 1st name
> >>>> l.sort()
>  ...
> > Though I can't say anything about speed.
> I can: it will be lousy.  Besides, for this example, just
> the "# 3)" call happens to have the same end result as
> 1 then 2 then 3, because sequences compare lexicographically.
Unfortunately --- thank God --- your're right !:-)
Think I've been taken by Brian Kransons's example:

  Kranson> >>> names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],
  Kranson> ['Rubble', 'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]
  Kranson> >>> names.sort() #this will sort by last name
  Kranson> >>> print names
  Kranson> [['Flintstone', 'Fred'], ['Flintstone', 'Wilma'], ['Rubble',
  Kranson> 'Barney'], ['Rubble', 'Betty'], ['Flintstone', 'Pebbles']]
  Kranson> ...
  Kranson> ...
  Kranson> >>> names=[['Flintstone', 'Fred'],['Flintstone', 'Wilma'],
  Kranson> ['Rubble', 'Barney'],['Rubble', 'Betty'],['Flintstone', 'Pebbles']]
  Kranson> >>> names.sort(lambda a, b: cmp(a[1], b[1])) #this will sort by 
  Kranson> first name
  Kranson> >>> print names
  Kranson> [['Rubble', 'Barney'], ['Rubble', 'Betty'], ['Flintstone', 'Fred'],
  Kranson> ['Flintstone', 'Pebbles'], ['Flintstone', 'Wilma']]

That made me believe, that changing his order of sorting would
be necessary to change the order of sorting result.

> The (printed) Python Cookbook's chapter on Sorting and
> Searching has a lot of useful and interesting info on
> such issues, particularly in Tim Peter's introduction.
> Alex

Think, I should learn that Cookbooks are not only
good to use in kitchen :-)

BTW Can one say under which circumstances the sort-function
happens to be not stable. I did some tries with 100 000 items
each with 3 or 5 random letters 'A' to 'Z' including some
equal items. But with the normal sort and the decorated 
sort and I couldn't find any results
that differed from each other?? (it took me more time 
to generate the list than to sort them !!)


More information about the Python-list mailing list