1Understand
The idea
Instead of writing a comparator, give sorted a key: the value to sort by. Tuples sort field by field, so key=lambda p: (-p.score, p.name) means "score descending, then name ascending". Sorting is stable, so equal keys keep their original order, which is often exactly the tie-break a problem asks for.
Intuition
sorted and list.sort take a key, not a comparator: a function that maps each item to the value you sort by. Tuples compare field by field, so one key can encode "primary descending, secondary ascending".
Python's sort is stable: equal keys keep their previous order. That often gives free tie-breaking if you sort in stages, but a single tuple key is clearer.
min/max accept the same key= idea. list.sort() returns None, it sorts in place; use sorted(a) when you need a new list.
What you will be able to do
- Sort by one or several keys
- Reverse one criterion by negating
- Know sort is stable
2See it
Walkthrough
Sort with a key tuple
people = [(90, "b"), (90, "a"), (80, "c")], score desc. Name asc.
1 / 4
Unsorted. Want highest score first; ties broken by name ascending.
Sorting is O(n log n). Computing the key once per element is fine; avoid O(n) work inside the key if you can precompute. Stability lets you sort by secondary key first, then primary, but a tuple key is usually simpler.
Read the walkthrough as text
Sort students. Each student is (name, score). Want highest score first; ties alphabetical by name.
In code:
students = [("Zoe", 90), ("Ann", 90), ("Bob", 85)]students.sort(key=lambda s: (-s[1], s[0]))# [("Ann", 90), ("Zoe", 90), ("Bob", 85)]
- Key for Zoe is
(-90, "Zoe"), for Ann(-90, "Ann"). -90ties, so"Ann" < "Zoe"decides the order.- Bob's
-85is larger (less negative), so he sorts later.
Negate numeric fields for descending; leave strings as-is for ascending.
3Recognise it
Kinds of problems (4)
Same pattern, different surfaces. Each row is a problem shape you should recognise, not only the first walkthrough example.
Single key
Example. Sort intervals by end time.
How. sorted(items, key=lambda x: x[1]), one callable picks the sort criterion.
Tuple keys for tie-breaking
Example. Sort by score desc, then name asc.
How. key=lambda p: (-p.score, p.name) encodes primary and secondary order in one tuple.
Descending on one field
Example. Largest values first without reverse=True on everything.
How. Negate numbers in the key (-x) while leaving string tie-breakers natural.
min/max with key
Example. Pick the longest word in a list.
How. max(words, key=len) scans once; no need to sort the entire collection.
Common mistakes
Failure modes the tutor watches for. Open the Common mistake tab in the walkthrough to watch one fail live.
Wrong key function or tuple ordering
Why it happens. Tuple ordering is subtle when one field should be descending.
How it fails. key=lambda p: (p.score, p.name) when you wanted highest score first, asc on score ranks the wrong way.
Fix. Negate numeric fields for descending: (-score, name); order tuple components left-to-right as tie-breakers.
Using the return value of list.sort()
Why it happens. Chaining feels natural: sorted = nums.sort().
How it fails. nums.sort(); return nums.sort() returns None even though nums is now sorted.
Fix. sorted(nums) returns a new list; nums.sort() sorts in place and returns None, assign only from sorted().
Unreadable lambdas
Why it happens. Inlining everything in a lambda saves naming a helper.
How it fails. key=lambda x: (x[1][0] if x[1] else 0, -len(x[2])), unreadable in an interview and easy to transpose.
Fix. Use def key_fn(x): with a doc comment in your head; one clear return tuple beats a nested lambda.
4Check yourself
Concept check
A short quiz on this lesson before you practise. Optional, and it does not gate coding.
Ready to practise?
Mastery comes from solving. The lesson is optional context.