Code

Sorting with key=

sorted(items) returns a new sorted list. Two keyword arguments make it powerful:

  • reverse=True sorts from biggest to smallest.
  • key= is a function that turns each item into the value to sort by.
words = ["moss", "ox", "lantern"]
sorted(words, key=len)            # ['ox', 'moss', 'lantern']
sorted(words, key=len, reverse=True)

For a quick custom key, write a lambda: a tiny one-line function with no name (more on these in the next chapter).

crew = [("Ada", 7), ("Bo", 9), ("Cy", 7)]
sorted(crew, key=lambda m: m[1])  # by level, lowest first

Need a tie-breaker? Return a tuple: Python compares the first part, then the next. Negate a number to flip just that part:

sorted(crew, key=lambda m: (-m[1], m[0]))
# [('Bo', 9), ('Ada', 7), ('Cy', 7)]  level high to low, then name A to Z

min and max take key= too: max(crew, key=lambda m: m[1]) returns the whole ("Bo", 9) tuple.

Python's sort is stable: items with equal keys keep their original order.

Assignment

  1. by_length(words): shortest word first (ties keep their order).
  2. ranked(crew): crew is a list of (name, level) tuples. Highest level first; equal levels sorted by name A to Z.
  3. strongest(crew): return the name of the member with the highest level.