⚡ Comprehensions & Iteration, lesson 4 of 5
Sorting with key functions
Sort, rank and pick winners by any rule you like.
10 min
2 exercises
2 quizzes
0/4 solved
Getting Python ready… examples can run in a moment.
sorted, min, max and list.sort accept a
key function. Python calls it on every item and
compares the results, while still returning the
original items:
key=len: by lengthkey=str.lower: alphabetically, ignoring casekey=lambda p: p["score"]: by a field
Different orders
Plain sorted puts capitals first ("Z" comes before
"a"). key=str.lower fixes that.
What key=len does
Before sorting: the words in their original order.
sorted(words, key=len)
Leaderboard
max with a key returns the whole record, not just the score.
What does this print?
Tie-breakers. Tuples compare item by item, so a key that returns a tuple sorts by the first value, then the second, and so on. To sort one part descending, negate it (works for numbers).
Highest score, then A to Z
Change the key to lambda s: s[0] to sort by name only.
Sort a dict by its values
counts.get is a function that looks up a key's value, so it works as a key!
What does this print?
Rank the products
Each product is (name, price, rating). Build:
cheapest_first: product names, lowest price first.best_rated: product names, highest rating first; on a tie, the cheaper one first.priciest: the name of the most expensive product (usemaxwith a key).
Sort by last letter
Write a function by_last_letter(words) that returns the
words sorted by their last letter, ignoring case.
Words with the same last letter keep their original order.