sorting the list by inner elements

Andrew Bennetts andrew-pythonlist at
Thu Mar 25 15:27:02 CET 2004

On Thu, Mar 25, 2004 at 07:31:16AM -0600, John Hunter wrote:
> >>>>> "ketulp" == ketulp baroda <ketulp_baroda at> writes:
>     ketulp> I like ur idea but this will work for only when inner list
>     ketulp> has only two elements. if inner list has five elements and
>     ketulp> i want to sort the whole list by 3rd element then how can
>     ketulp> i do this ?
> The general approach is to arrange the elements in the order you want
> them sorted, sort them, and then revert to original order.  So if you
> have 5 elements, and you want them sorted by the 3rd, put the 3rd
> first.  If any two of the first elements are the same, the second
> element of the list will break the tie, and so on.
> Supposing you want to sort by the 3rd element, and you don't care
> about the relative order of the other fields
>   # swap the first an 3rd elements
>   tmp = [ (e[2], e[1], e[0], e[3], e[4]) for e in seq]
>   tmp.sort()
>   # swap them back
>   seq = [ (e[2], e[1], e[0], e[3], e[4]) for e in tmp]

That's more complicated than it needs to be for ketulp's use-case.

tmp = [(e[2], e) for e in seq]
seq = [t[1] for t in seq]


More information about the Python-list mailing list