[Tutor] sorting based on elements which are nested in a list

Lie Ryan lie.1296 at gmail.com
Sun Apr 3 16:55:43 CEST 2011

On 04/04/11 00:14, ranjan das wrote:
> I have a list which I want to sort based on ('a','b','c') first and then
> based on (1,2,3)
> How do i do these using itemgetter() since the list is nested
> A=[('k3', ['b', 3]), ('k2', ['a', 1]), ('k1', ['a', 3]), ('k4', ['c', 2])]
> The solution I am looking for is 
> A_sorted=[ ('k2', ['a', 1]), ('k1', ['a', 3]), ('k3', ['b', 3]) ('k4',
> ['c', 2])]

itemgetter() is only a convenience function, you can make your own
function, like this:

A_sorted = sorted(A, key=lambda i: (i[1][0], i[1][1]))

or in your particular case, since list is compared in lexicographical
order, this would actually work:

A_sorted = sorted(A, key=itemgetter(1))

More information about the Tutor mailing list