The sorted
built-in and sort
list method can order lists based on the returned value of a function called on each element prior to making comparisons. This function is passed as the key
argument. For example, sorting a list of strings is case-sensitive by default:
>>> sorted('Nobody expects the Spanish Inquisition'.split())
['Inquisition', 'Nobody', 'Spanish', 'expects', 'the']
We can make the sorting case-insensitive, however, by passing each word to the str.lower
method:
>>> sorted('Nobody expects the Spanish Inquisition'.split(), key=str.lower)
['expects', 'Inquisition', 'Nobody', 'Spanish', 'the']
(of course, key=str.upper
would work just as well). Note that the list elements themselves are not altered: they are being ordered based on a lower-case version of themselves. We do not use parentheses here, as in str.lower()
, because we are passing the function itself
to the key
argument, not calling it directly.
It is typical to use lambda
expressions to provide simple anonymous functions for this purpose. For example, to sort a list of atoms as (element symbol, atomic number) tuples in order of atomic number (the second item in each tuple):
>>> halogens = [('At', 85), ('Br', 35), ('Cl', 17), ('F', 9), ('I', 53)]
>>> sorted(halogens, key=lambda e: e[1])
[('F', 9), ('Cl', 17), ('Br', 35), ('I', 53), ('At', 85)]
Here, the sorting algorithm calls the function specified by key
on each tuple item to decide where it belongs in the sorted list. Our anonymous function simply returns the second element of each tuple, and so sorting is by atomic number.