sorting list of tuples by second (third...) tuple item

Justin Sheehy justin at
Thu Feb 14 15:25:57 EST 2002

stojek at (Marcus Stojek) writes:

> How can I sort a list of tuples (all tuples have 4 float items)
> by the second (or third or n-th) tuple item. And I have to
> do it fast.

Python's builtin sort is fairly fast, all you need to handle is the indexing.

The straightforward way would be:

lst.sort(lambda a,b: cmp(a[2], b[2]))

or if you don't like lambda:

def cmp3(a, b):
    return cmp(a[2], b[2])

If you want more speed, you may want to decorate the list first:

newlst = [(x[2], x) for x in lst]
lst = [x[1] for x in newlst]



More information about the Python-list mailing list