Lesson 18 of 34 · Lists & Tuples
Boss: Build a Python Leaderboard
Coilrank the Tournament Naga blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
Coilrank the Tournament Naga lost the Hollow's great tournament — and in a fit of rage, it scrambled every result on the scoreboard. Rebuild the leaderboard — sorted, ranked and summarised — and send the sore loser slithering home.
Battle plan
Tournament results are a list of (name, score) tuples:
results = [("Bo", 75), ("Ada", 98), ("Cy", 88), ("Di", 98), ("Ed", 60)]
You'll combine sorted() with a key function, slicing, tuple unpacking and list comprehensions. One trick is worth knowing: when a key function returns a tuple, Python sorts by the first item, then uses the second to break ties. Negating a number flips its order, so the key (-score, name) means highest score first, then alphabetical.
Assignment
Write four functions. None of them may modify the list they receive.
1. leaderboard(results, n=3) returns the top n entries as (name, score) tuples, sorted by score from highest to lowest. Equal scores are ordered by name, A to Z. If there are fewer than n entries, return them all.
2. format_leaderboard(results, n=3) returns a list of strings for the top n entries in the form "<rank>. <name> - <score>", with ranks starting at 1.
3. average_score(results) returns the average score rounded to one decimal place, or 0.0 for an empty list.
4. players_above(results, threshold) returns the names of all players whose score is strictly greater than threshold, sorted alphabetically.
leaderboard(results) # [("Ada", 98), ("Di", 98), ("Cy", 88)]
format_leaderboard(results) # ["1. Ada - 98", "2. Di - 98", "3. Cy - 88"]
average_score(results) # 83.8
players_above(results, 80) # ["Ada", "Cy", "Di"]Premium lesson
Unlock the full Learn Python course
- All 34 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.
Lesson last updated on .