Sorting by a key: sorted, min, max
🌍 In real life. A sports teacher lines the class up "by height", or "by roll number", or "by birthday". It's the same children every time; only the rule for what to compare changes. And to find the tallest, she doesn't need the whole line, just the one with the biggest height.
In Python, that rule is a function you pass as key=.
The idea in one sentence: sorted, min and max take a key= function that says what to compare: Python works out each item's key, compares the keys, and gives back the items themselves.
Its words:
key=: a function called once on each item, likelenorlambda p: p[1]- key value: what that function gives back for an item, like 4 for "kiwi"
- stable sort: items with equal keys keep the order they had
- tuple key:
lambda w: (len(w), w)compares by length, then alphabetically
Step by step, for sorted(["kiwi", "fig", "apple", "pear"], key=len):
- Work out each key: kiwi → 4, fig → 3, apple → 5, pear → 4.
- Order the items by key, smallest first; kiwi and pear tie, so they keep their order.
- The result is
['fig', 'kiwi', 'pear', 'apple'].
words = ["kiwi", "fig", "apple", "pear"]
print(sorted(words, key=len))
print(sorted(words, key=lambda w: w[-1]))Add reverse=True to sort largest first. min and max take a key too: they give back the item whose key is smallest or largest.
people = [("Ana", 9), ("Bo", 12), ("Cy", 7)]
print(sorted(people, key=lambda p: p[1]))
print(sorted(people, key=lambda p: p[1], reverse=True))
print(max(people, key=lambda p: p[1]))
print(min(people, key=lambda p: p[1])[0])Items with equal keys keep the order they had. To break ties another way, let the key give back a tuple: tuples compare their first values, then their second, and so on.
words = ["pear", "fig", "kiwi", "date"]
print(sorted(words, key=len))
print(sorted(words, key=lambda w: (len(w), w)))What it costs. The key function runs once per item, not once per comparison, so an expensive key is still only n calls. Sorting itself is about n × log₂ n comparisons (Lesson 8.4). min and max with a key are one pass: n key calls and n comparisons.
Mistakes and edge cases.
- Calling the key.
key=len()givesTypeError: len() takes exactly one argument (0 given). Pass the function:key=len. - Expecting the keys back.
sorted(words, key=len)gives words, not lengths. - reverse=True on min.
minandmaxhave noreverse; use the other one. - max of nothing.
max([], key=len)gives a ValueError; check the list isn't empty first.
Quiz
What does this print?
print(sorted(["bb", "a", "ccc"], key=len))What does this print?
print(max([3, -7, 5], key=abs))What does this print?
print(sorted(["to", "be", "a"], key=len))What does this print?
pets = [("cat", 4), ("bird", 2), ("dog", 9)] print(min(pets, key=lambda p: p[1])[0])What does
key=decide?- What each item is compared by
- How many items to keep
- The name of the result
Which line stops this program with an error?
words = ["kiwi", "fig", "apple"] short_first = sorted(words, key=len()) print(short_first)
Coding tasks
Write
by_length(words)that returns the words sorted shortest first. Words of equal length keep their order.peopleis a list of(name, age)tuples. Writeoldest(people)that returns the name of the oldest person (the first one, if there's a tie).Write
sort_people(names, heights)that returns the names sorted by height, tallest first.heights[i]is the height ofnames[i], and no two heights are equal.