Sub topic 4
Sorting and ranking with key functions
This chapter assumes you can define functions with def, write a basic lambda, and work with lists, tuples and dictionaries. It builds on the idea that a function is a value you can pass to another function. Here the receiving function is sorted, min or max, and the value you pass is called a key function.
What a key function does
A key function takes one item and returns the value Python should use to compare that item with others. You pass it with the key= parameter. Python never changes your items. It only decides their order from the keys.
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=lambda p: p[1]))
# [('pear', 1), ('fig', 2), ('apple', 3)]Without key, Python compares the tuples themselves, so they sort by the first element (the fruit name). With the lambda, each tuple is replaced by its second element for the comparison, so the quantities decide the order.
Python calls the key function exactly once per item, then sorts using the stored keys. You can see this by recording the calls.
calls = []
def key(x):
calls.append(x)
return x % 3
print(sorted([5, 3, 4, 1], key=key)) # [3, 4, 1, 5]
print(calls) # [5, 3, 4, 1]Each of the four numbers appears once in calls, even though sorting makes more than four comparisons. This is why a key function is usually faster than an old-style comparison function, which runs on every comparison. It also means an expensive key function costs one call per item, not one per comparison.
Any one-argument callable works
A lambda is only one option. Anything callable with a single argument can be a key, including built-in functions and methods.
words = ["banana", "Cherry", "apple", "fig"]
print(sorted(words)) # ['Cherry', 'apple', 'banana', 'fig']
print(sorted(words, key=str.lower)) # ['apple', 'banana', 'Cherry', 'fig']
print(sorted(words, key=len)) # ['fig', 'apple', 'banana', 'Cherry']The default string order puts every uppercase letter before every lowercase letter, so "Cherry" comes first. str.lower converts each word to lowercase for the comparison only, and the output still shows the original spelling. For text that may contain non-English letters, str.casefold is a more thorough version of the same idea.
Notice the last line. "banana" and "Cherry" both have length 6, and "banana" stays ahead of "Cherry", as it was in the input. That is stability, covered below.
sort versus sorted
There are two ways to sort a list, and both accept key and reverse.
| Feature | `sorted(iterable, ...)` | `list.sort(...)` |
|---|---|---|
| Input | Any iterable | Lists only |
| Result | Returns a new list | Sorts in place, returns `None` |
| Original data | Unchanged | Changed |
A common mistake is writing items = items.sort(key=...). That sets items to None. Use items.sort(key=...) on its own line, or items = sorted(items, key=...).
Stability
Python's sort is stable. Items whose keys are equal keep the relative order they had in the input. This holds even with reverse=True: equal items still appear in their original order, because Python does not simply reverse the final list.
people = [("Ana", "Lisbon"), ("Ben", "Oslo"), ("Cy", "Lisbon"), ("Di", "Oslo")]
print(sorted(people, key=lambda p: p[1]))
# [('Ana', 'Lisbon'), ('Cy', 'Lisbon'), ('Ben', 'Oslo'), ('Di', 'Oslo')]Within each city, the people appear in the same order as the input. Stability lets you sort in several passes, which is useful for the next section.
Sorting by more than one criterion
When the key returns a tuple, Python compares the tuples element by element. The first element decides, and later elements only break ties.
scores = [
{"name": "Ana", "score": 90, "age": 21},
{"name": "Ben", "score": 85, "age": 19},
{"name": "Cy", "score": 90, "age": 19},
{"name": "Di", "score": 85, "age": 22},
]
ranked = sorted(scores, key=lambda r: (r["score"], r["name"]))
print([r["name"] for r in ranked]) # ['Ben', 'Di', 'Ana', 'Cy']This sorts by score ascending, then by name. To get the highest score first with names still ascending, you need mixed directions. reverse=True would flip both. There are two ways to handle it.
For numeric fields, negate the number in the key.
ranked = sorted(scores, key=lambda r: (-r["score"], r["name"]))
print([r["name"] for r in ranked]) # ['Ana', 'Cy', 'Ben', 'Di']For fields that cannot be negated, such as strings, use two stable passes. Sort by the least important field first, then by the most important.
step1 = sorted(scores, key=lambda r: r["name"])
step2 = sorted(step1, key=lambda r: r["score"], reverse=True)
print([r["name"] for r in step2]) # ['Ana', 'Cy', 'Ben', 'Di']The second pass reorders by score only. Stability keeps the name order from the first pass among equal scores.
Finding the smallest and largest with min and max
min and max accept the same key argument. They return the item itself, not the key.
best = max(scores, key=lambda r: r["score"])
youngest = min(scores, key=lambda r: r["age"])
print(best["name"], youngest["name"]) # Ana BenTwo details matter here:
- When several items tie,
minandmaxreturn the first one they meet. Ana and Cy both have a score of 90, and Ana is returned. - On an empty iterable, both raise
ValueError. Passdefault=to return a fallback instead.
print(max([], key=len, default=None)) # NoneRanking the top few
To get the top N items, you can sort and slice, or use heapq.nlargest and heapq.nsmallest. They accept key too.
import heapq
top_two = heapq.nlargest(2, scores, key=lambda r: r["score"])
print([r["name"] for r in top_two]) # ['Ana', 'Cy']nlargest gives the same result as sorted(..., reverse=True)[:n], including tie order. It is more efficient when N is small compared with the size of the data. For a small list, a plain sorted(...)[:n] is clearer and fast enough.
Keys that return booleans
A key may return any value that can be compared. Booleans compare as False < True, so a true/false key moves items into groups.
nums = [1, 2, 3, 4, 5, 6]
print(sorted(nums, key=lambda n: n % 2 == 0)) # [1, 3, 5, 2, 4, 6]Odd numbers have key False, so they come first. Stability keeps each group in its original order. This pattern is a quick way to move certain items to the front or back without disturbing the rest.
Handling missing values
Python 3 refuses to compare None with a number, so a list containing both fails.
values = [3, None, 1, 2]
# sorted(values) # TypeError: '<' not supported between 'NoneType' and 'int'
print(sorted(values, key=lambda v: (v is None, v if v is not None else 0)))
# [1, 2, 3, None]The key returns a tuple. The first element is False for real numbers and True for None, so None goes last. The second element orders the real numbers. For None it is a placeholder 0, which never gets compared against a real number because the first elements already differ. To put None first instead, use v is not None as the first element.
Common errors
Other errors to watch for:
- Keys that cannot be compared. If the keys for different items have different types, such as an integer and a string, sorting raises
TypeError. Make the key return one consistent type. - A key that takes more than one argument. The function receives exactly one item. To sort
(name, score)tuples, take the tuple as one parameter and index it, as inlambda p: p[1]. Writinglambda name, score: scorefails. - Expecting the key's output.
sortedreturns the original items, not the keys. If you want the keys, build them separately. - Mutating inside the key. A key function with side effects, such as changing a shared list, behaves unpredictably. Keep it a pure calculation.
When you need a comparison function
Some orderings are easiest to express as "does a come before b?". Python 3 has no cmp= parameter, but functools.cmp_to_key converts an old-style comparison function into a key.
from functools import cmp_to_key
def by_length_then_alpha(a, b):
if len(a) != len(b):
return len(a) - len(b)
return (a > b) - (a < b)
words = ["pear", "fig", "apple", "kiwi"]
print(sorted(words, key=cmp_to_key(by_length_then_alpha)))
# ['fig', 'kiwi', 'pear', 'apple']The comparison function returns a negative number if a goes first, zero if they are equal, and a positive number if b goes first. Prefer a tuple key when one will do. In this example key=lambda w: (len(w), w) gives the same result and is shorter. Reach for cmp_to_key only when no simple key expresses the rule.
Summary
key=takes a one-argument callable and sorts by what it returns.- The key function runs once per item, and the sort is stable.
- Tuple keys sort by several criteria. Use negation or two passes for mixed directions.
min,max,heapq.nlargestandheapq.nsmallestuse the samekeyconvention.- Handle
Noneand mixed types in the key, not after the failure.
Exercise
Given items = [("pen", 4, 1.5), ("book", 2, 12.0), ("cup", 4, 3.0), ("bag", 1, 20.0)], where each tuple is (name, quantity, price), write one sorted call that orders the items by quantity from highest to lowest, and breaks ties by name from A to Z. What is the resulting list of names?
Show answer
Use sorted(items, key=lambda t: (-t[1], t[0])). The names come out as ['cup', 'pen', 'book', 'bag']. Quantity 4 is the highest, and "cup" comes before "pen" alphabetically. Then comes "book" (quantity 2) and "bag" (quantity 1).
Exercise
A list temps = [18.5, None, 21.0, 16.2, None] holds readings, and None marks a missing reading. Write a call that returns the readings sorted from lowest to highest with the None values at the end. Then say what max(temps, key=lambda t: t) does with this list and why.
Show answer
Use sorted(temps, key=lambda t: (t is None, t if t is not None else 0)), which gives [16.2, 18.5, 21.0, None, None]. The max call raises TypeError, because max has to compare None with a float and Python 3 does not allow that comparison.