Sub topic 2
Keys, Comparators and Equal Elements
This chapter assumes you can write a small Python program, pass a function as an argument, and read Big-O notation. It covers the two ways you tell a sort what "smaller" means, and what it means for two elements to count as "equal" when the sort sees them.
Two ways to describe an order
A comparison sort only needs one question answered: does a come before b? Libraries let you answer that question in one of two forms.
A key function takes one element and returns a value the language already knows how to compare, such as a number, a string or a tuple. The sort compares the keys, not the elements.
A comparator takes two elements and returns their relative order directly. In Python, Java and JavaScript it returns a negative number, zero or a positive number. In C++ and Go it returns a boolean "less than" answer instead.
from functools import cmp_to_key
words = ["pear", "Fig", "apple", "kiwi", "Date"]
# Key function: one element in, one comparable value out.
print(sorted(words, key=len))
# ['Fig', 'pear', 'kiwi', 'Date', 'apple']
print(sorted(words, key=str.lower))
# ['apple', 'Date', 'Fig', 'kiwi', 'pear']
# Comparator: two elements in, negative / zero / positive out.
def by_length(a, b):
return len(a) - len(b)
print(sorted(words, key=cmp_to_key(by_length)))
# ['Fig', 'pear', 'kiwi', 'Date', 'apple']Python 3 accepts only key functions, so cmp_to_key wraps a comparator in an object whose < operator calls it.
Which form to choose
Key functions are usually simpler and faster. Python calls the key function once per element and caches the result, so the cost is n calls. A comparator runs on every comparison, which is roughly n log n calls. Use a comparator when the order can't be described as a single value, for example when a rule depends on both elements at once.
Each language shapes its comparator differently:
| Language | Key-based API | Comparator shape | Column | Column |
|---|---|---|---|---|
| Python | `sorted(xs, key=f)` | `cmp_to_key(f)`, `f(a, b)` returns int | ||
| Java | `Comparator.comparing(f)` | `compare(a, b)` returns int | ||
| C++ | none built in, use a projection in C++20 `std::ranges::sort` | `less(a, b)` returns bool | ||
| JavaScript | none built in | `(a, b) => number` | ||
| Rust | `sort_by_key(f)` | `sort_by(\ | a, b\ | ...)` returns `Ordering` |
| Go | none built in | `less(i, j)` returns bool, using indexes |
Equal is not identical
When a comparator returns zero, or when neither less(a, b) nor less(b, a) holds, the sort treats a and b as equivalent. That does not mean they are the same value. Under key=len, the strings "pear", "kiwi" and "Date" are all equivalent because each has length 4, even though they are different words.
This is where sorting gets subtle. The order says nothing about how equivalent elements should be arranged among themselves, so any arrangement of pear, kiwi and Date is a correctly sorted output under key=len. Which arrangement you actually get depends on the algorithm. The next chapter looks at exactly that question.
Reversing and refining keys
You can reverse an order with reverse=True, or for numbers by negating the key (key=lambda r: -r.price). Returning a tuple refines the order. Python compares tuples element by element, so key=lambda w: (len(w), w.lower()) breaks length ties alphabetically and leaves fewer equivalent pairs. A later chapter covers multi-key sorting in full.
Exercise
Given words = ["Bob", "alice", "bea", "Al"] and key=lambda s: s[0].lower(), which elements does the sort treat as equivalent, and how many different outputs count as correctly sorted?
Show answer
The keys are "b", "a", "b", "a". "alice" and "Al" are equivalent (key "a"), and "Bob" and "bea" are equivalent (key "b"). All "a" words must come before all "b" words, and each pair can appear in either internal order, so there are 2 × 2 = 4 correctly sorted outputs.
Exercise
Why is sorted(xs, key=f) usually faster than sorted(xs, key=cmptokey(g)) for an equally expensive f and g?
Show answer
Python calls the key function f once per element (n calls) and caches the keys. The wrapped comparator g runs on every comparison, about n log n calls, so it does more work as n grows.