Lesson 3 of 10

Sorting with a key

Goal

The key parameter decides what gets compared

01

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.

02

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
  1. by_score runs from the highest score to the lowest
  2. Ties in by_score keep their original order
  3. ranked is sorted by score descending, then by name A to Z
  4. students keeps its original order
  5. Sorted with key=, not by manual comparison
main.py
OutputPython (Pyodide)

Loading Python. This only happens once. Your browser keeps it after that.

–/5

Checks start once the environment is ready.

5 checks listed under “Your task”.