──────────────────────────────────────

11. Wildlife Survey Data Lab · Sort a Leaderboard Fairly

Rank records by a primary value and an explicit tie-breaker.

Lesson files · lessons/search-sort-summarise/sort-with-ties

Before you start
- Read a name and number from a tuple.
- Return a value from a helper function.
- Join several names into one line.

By the end
- Rank team records by points and print their names in that order.
- Use the result to explain which name comes first when points are tied.

Where you can use it
Publish a quiz leaderboard that orders high scores first and uses team names when scores match.

sorted(items, key=...) evaluates a key for every item. A tuple key compares its first value, then its second if needed. Use a negative count for descending counts and leave the name unchanged for alphabetical ties.

Predict
Which team comes first among teams with 2 points?
- Comets.
- Owls.

Worked example (example.py)

def rank(item):
    name, points = item
    return (-points, name)

print(sorted([("Owls", 2), ("Comets", 2), ("Robins", 5)], key=rank))


Example result
[('Robins', 5), ('Comets', 2), ('Owls', 2)]

Use the rank key and print just the three team names separated by comma-space.

Starter program (starter.py)

def rank(item):
    name, points = item
    return (-points, name)

print(sorted([("Owls", 2), ("Comets", 2), ("Robins", 5)], key=rank))


Hint
Loop over the sorted pairs or use a comprehension that keeps only the name.

Case 1. Try the sample
Input
(No input.)
Expected output
Robins, Comets, Owls

Stretch
Give the Owls 6 points and predict the new order.

Reflect
Why does reverse=True on a tuple key affect both parts of the order?

Check your prediction
Comets. The tie-break compares the names alphabetically.
