A key function is a callable that receives one list item and returns the value used to order that item. It lets sorting follow a property other than the items' default comparison. section 5.4.1
Use a key function when the default ordering is not the ordering you need:
- Define a function with one parameter and return the comparison value, such as len(string). section 5.4.1
- Pass the function to sort with the key keyword: word_list.sort(key=comp_num_of_chars). section 5.4.1
- For a short, one-use rule, replace the named function with a lambda, such as key=lambda x: len(x). section 5.4.1
- Keep the key calculation simple when sorting large datasets, because the function is called repeatedly and complex work can slow sorting. section 21.4.2
Sort words by length
word_list = ['Python', 'is', 'better', 'than', 'C'] word_list.sort(key=lambda x: len(x)) print(word_list) ['C', 'is', 'than', 'Python', 'better'] The default sort produces lexicographic order; the key function makes string length determine the order. section 5.4.1
Change the comparison value
lines.sort(key=str.lower) This sorts text without treating uppercase and lowercase as different ordering values. A key can also select part of each item, as in key=lambda x: x[5:]. section 21.4.2
word_list.sort(key=lambda x: len(x))
Inspect the smallest useful lambda form for a key function. section 5.4.1

