# [Tutor] Newbie: Sorting lists of lists

Mark Tolonen metolone+gmane at gmail.com
Thu Jun 19 17:05:34 CEST 2008

```"Kent Johnson" <kent37 at tds.net> wrote in message
news:1c2a2c590806181754g3f1c5e3em677ab4ee8df3a192 at mail.gmail.com...
> On Wed, Jun 18, 2008 at 8:30 PM, Keith Troell <ktroell at mac.com> wrote:
>> Let's say I have a list of lists l == [[1, 2, 3], [2, 3, 1], [3, 2, 1],
>> [1,
>> 3, 2]]
>>
>> If I do a l.sort(), it sorts on the first element of each listed list:
>>
>>>>> l.sort()
>>>>> l
>> [[1, 2, 3], [1, 3, 2], [2, 3, 1], [3, 2, 1]]
>>
>>
>> How can I sort on the second or third elements of the listed lists?
>
> Use the key= parameter of sort to specify the sort key.
> operator.itemgetter is convenient for the actual key:
>
> In [3]: from operator import itemgetter
> In [4]: l.sort(key=itemgetter(1))
> In [5]: l
> Out[5]: [[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]]
>
> A longer explanation is here:
> http://personalpages.tds.net/~kent37/kk/00007.html
>
> Kent
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>

You can use a lambda that builds the key you want to sort on from the
original element:

>>> L=[[1,2,3],[2,3,1],[3,2,1],[1,3,2]]

Sort on 2nd value:

>>> sorted(L,key=lambda x: x[1])
[[1, 2, 3], [3, 2, 1], [2, 3, 1], [1, 3, 2]]

Sort on 2nd, then by 3rd value

>>> sorted(L,key=lambda x: (x[1],x[2]))
[[3, 2, 1], [1, 2, 3], [2, 3, 1], [1, 3, 2]]

-Mark

```