Lesson 3 of 10
Sorting with a key
- 13 min
- 5 checks
- 3 hints
- Go to task
Goal
The key parameter decides what gets compared
Explanation
sorted() returns a new sorted list and leaves the original alone, while .sort() sorts the list in place and returns None. That's where the classic mistake items = items.sort() comes from.
key= takes a function that gets called on every item, and Python compares the items by whatever that function returns. The shortest way to write it is a lambda, a nameless one-line function such as key=lambda s: s["score"]. And reverse=True flips the direction of the sort.
To sort by more than one criterion, return a tuple. Python compares the first element, and only on a tie moves on to the next one. For example, key=lambda s: (s["city"], -s["score"]) sorts by city, then by score from high to low within each city, because the minus sign reverses the order of that number alone.
Sorting in Python is stable: two items with equal keys keep their original order, even with reverse=True. If you flip the result with [::-1] instead, their order flips along with it and that guarantee is gone.
Your task
Build by_score with the students from the highest score to the lowest, keeping tied students in their original order. Then build ranked, sorted by score from high to low, with ties broken alphabetically by name. Use sorted with key= for both, and don't change students.
Checks
5 checks- by_score runs from the highest score to the lowest
- Ties in by_score keep their original order
- ranked is sorted by score descending, then by name A to Z
- students keeps its original order
- Sorted with key=, not by manual comparison