Python Notes and Examples

Sorting

>>> data = [[10, 'a'], [8, 'b'], [9, 'c']]
>>> data
[[10, 'a'], [8, 'b'], [9, 'c']]

>>> data.sort()
>>> data
[[8, 'b'], [9, 'c'], [10, 'a']]

>>> data.sort(key=lambda p: p[1])
>>> data
[[10, 'a'], [8, 'b'], [9, 'c']]

Notice that the job of the “key” function we pass to sort is only to get or compute the representative value we want to sort on. That is, items are sorted by keyfn(item), rather than item.

In the old days, the sort method took a cmp arg, but that’s no longer supported — just use a key function.

See also the sorting howto in the Python docs.