Sorting with key functions

Comprehensions & Iteration, lesson 4 of 5

⚡ 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 length
  • key=str.lower: alphabetically, ignoring case
  • key=lambda p: p["score"]: by a field
Example

Different orders

Plain sorted puts capitals first ("Z" comes before "a"). key=str.lower fixes that.

Walkthrough

What key=len does

wordsbananaFigappleCherrykiwi01234len(w)01234
Step 1 of 3

Before sorting: the words in their original order.

key value
tie

sorted(words, key=len)

Example

Leaderboard

max with a key returns the whole record, not just the score.

Quiz

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).

Example

Highest score, then A to Z

Change the key to lambda s: s[0] to sort by name only.

Example

Sort a dict by its values

counts.get is a function that looks up a key's value, so it works as a key!

Quiz

What does this print?

Exercise

Rank the products

Each product is (name, price, rating). Build:

  1. cheapest_first: product names, lowest price first.
  2. best_rated: product names, highest rating first; on a tie, the cheaper one first.
  3. priciest: the name of the most expensive product (use max with a key).
Exercise

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.