Python Notes and Examples
← prev | next →     Top-level ToC     /sorting.html     (printable version)
>>> data = [[10, 'a'], [8, 'b'], [9, 'c']]
>>> data
[[10, 'a'], [8, 'b'], [9, 'c']]
>>> data.sort(key=lambda p: p[0])
>>> data
[[8, 'b'], [9, 'c'], [10, 'a']]

Notice that the job of the keyfn we pass to [].sort is only to get or compute the representative value we want to sort on for the given item. That is, items are sorted by keyfn(item), rather than just by item.

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

See also the sorting howto in the Python docs.