Sort with keys and tie-breaks
Many questions say "rank these" and then add rules for ties. Python's sorted does this with a key: a function that turns each item into the value to compare.
words = ["pear", "fig", "apple", "kiwi"] sorted(words, key=len) # shortest first sorted(words, key=lambda w: (len(w), w)) # length, then a-z
A tuple key compares its first part, and only on a tie looks at the next part. That is how you write a tie-break. To sort one part descending inside a tuple, negate a number: (-points, name). reverse=True flips the whole key, which is wrong when the parts need different directions.
sorted is stable: items with equal keys keep their original order. State the tie-break you need and put it in the key, so nothing depends on luck.Watch the table: pear and kiwi both have 4 letters, so the second part of the key decides their order.
See it run
names = ["pear", "fig", "apple", "kiwi"] by_len = sorted(names, key=len) by_both = sorted(names, key=lambda w: (len(w), w)) longest_first = sorted(names, key=len, reverse=True)
Three sorts of the same list. Look at where pear and kiwi (both 4 letters) land each time.
Practice sort with keys and tie-breaks
Exercise 1
A game keeps a leaderboard as a list of [name, points] pairs. Write solution(entries) to return the names only, as a list, best player first.
Rules:
- More points ranks higher.
- Players with equal points are ordered by name, alphabetically (a to z).
- Names are distinct lowercase words; points are integers and may be zero or negative.
- An empty
entriesgives[].
Constraints: 0 ≤ len(entries) ≤ 10^4.
Example: solution([["mo", 5], ["bea", 9], ["al", 5]]) returns ["bea", "al", "mo"] because bea has the most points, and al and mo tie on 5 so al comes first.
Exercise 2
A courier sorts parcels, each given as [id, weight, priority], into a loading order. Write solution(parcels) to return the ids in the order they should be loaded.
Rules:
- A higher
priorityloads first. - On equal priority, the lighter parcel (smaller
weight) loads first. - If both are equal, the smaller
idloads first. - Ids are distinct integers. An empty list gives
[].
Constraints: 0 ≤ len(parcels) ≤ 10^4; weights and priorities are integers from 0 to 10^6.
Example: solution([[4, 10, 1], [2, 5, 2], [7, 5, 2], [1, 3, 1]]) returns [2, 7, 1, 4]. Priority 2 loads first (ids 2 and 7 tie on weight, so id 2 is first), then priority 1 (id 1 weighs 3, id 4 weighs 10).
Exercise 3
Warehouse shelf labels are lowercase letters followed by a number, like "aisle12" or "bin7". Write solution(labels) to return a new list with the labels in natural order.
Rules:
- Compare the letters part first, alphabetically (
"bin"comes before"bina"). - If the letters are equal, compare the number as a number, smallest first (
"bin9"before"bin10"). - Every label has one or more letters then one or more digits, and the number has no leading zeros.
- Equal labels may appear more than once; keep them all. An empty list gives
[].
Constraints: 0 ≤ len(labels) ≤ 10^4; numbers are below 10^9.
Example: solution(["bin7", "aisle12", "aisle9", "bin10"]) returns ["aisle9", "aisle12", "bin7", "bin10"].
The explanation and tasks are public. Running this lesson requires an account with course access.
Practice
Loading Python…Visualizer Watch your code run line by line
Run your code, then choose Play to follow its execution.