[Tutor] Newbie: Sorting lists of lists

Kent Johnson kent37 at tds.net
Thu Jun 19 02:54:04 CEST 2008


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


More information about the Tutor mailing list