sorted, lambda & tuple keys
Choose a useful sorting key
Lesson 14 of 20 · 11 min · Module 5: A more expressive Python toolkit
A sorting key expresses which part of a record determines its order. A tuple key can make ties predictable.
Start this lesson →Free. No installation: you write and run the code in your browser, and it is checked automatically.
By the end, you’ll be able to…
- Describe an order with a key function
- Use tuple keys for consistent ties
The idea
sorted(records, key=...) returns a new list. Python compares tuple keys from left to right, moving to the next item only when earlier items compare equal.
names = ["Sam", "Alex", "Mia"]
print(sorted(names, key=lambda name: len(name)))
01Separate the record from its key
The output still contains the original session dictionaries. The key function supplies comparison values; it does not replace each dictionary.
02Read a tuple key in priority order
Minutes is the primary rule. Name is considered only when the durations are equal, so the brief and key have the same order.
03Choose a non-mutating operation
list.sort changes its list and returns None. sorted creates a new list, which matches the contract of this exercise.
Your turn
ordered_sessions(sessions). Each dictionary has a name and numeric minutes. Return a new list ordered by minutes ascending, then name ascending. Keep the original list order.What the checks look for
- Orders durations and breaks ties by name
- Leaves the source list unchanged
- Handles an empty list
Take this with you
A sorting key states what matters first, second, and next.
Go a little further
Add a descending duration option while keeping names ascending for ties.