liveBook · Manning

Key function

As explained in The Quick Python Book, Fourth Edition

A key function is a callable that maps each item to a value used to determine that item's ordering during sorting.

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

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Explains the one-argument return rule, named and lambda syntax, applications, and repeated-call performance cost.
Examples
Demonstrates sorting words by length, text case-insensitively, or by a substring of each line.
What it assumes
Assumes functions, function arguments, string length, and basic lambda syntax.
What you can do after
Apply it via Python sorting methods to order items by a computed property.
How it connects
Connects key functions to sorting, the sort method, the sorted function, lambda functions, and lexicographic ordering.

Also explained in

Compare how 2 books explain key function →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.