The optional key
parameter to sort
/sorted
is a function. The function is called for each item and the return values determine the ordering of the sort
>>> lst = [['John', 2], ['Jim', 9], ['Jason', 1]]
>>> def my_key_func(item):
... print("The key for {} is {}".format(item, item[1]))
... return item[1]
...
>>> sorted(lst, key=my_key_func)
The key for ['John', 2] is 2
The key for ['Jim', 9] is 9
The key for ['Jason', 1] is 1
[['Jason', 1], ['John', 2], ['Jim', 9]]
taking the print
out of the function leaves
>>> def my_key_func(item):
... return item[1]
This function is simple enough to write "inline" as a lambda function
>>> sorted(lst, key=lambda item: item[1])
[['Jason', 1], ['John', 2], ['Jim', 9]]