Sorting by key
key, sorting by several fields and stability.
sorted and sort take a key parameter: a function that returns, for each element, the value to compare by. The elements themselves do not change:
words = ["bb", "a", "ccc"]
print(sorted(words, key=len)) # ['a', 'bb', 'ccc']
print(sorted(words, key=str.lower))
key=len compares lengths, key=str.lower compares strings ignoring case.
Tuples are compared element by element from left to right. That is why a tuple key sorts by several fields at once:
players = [("Ann", 5), ("Bob", 7), ("Cid", 5)]
ranked = sorted(players, key=lambda p: (-p[1], p[0]))
print(ranked) # [('Bob', 7), ('Ann', 5), ('Cid', 5)]
The minus before the number gives descending order by score, and with equal scores the name goes alphabetically. A minus does not work for strings, but the same order can be achieved with two sorts in a row.
Sorting in Python is stable: elements with an equal key keep their original order. The several-passes technique relies on this. You first sort by the secondary field, then by the main one, and the order within the groups is kept.
min and max also take a key: max(players, key=lambda p: p[1]) returns the whole player with the highest score, not just the number.
Practice
Ignoring case
What does the program print?
print(sorted(["Bob", "amy", "Cid"], key=str.lower))Stable sorting
What does it mean that sorting in Python is stable?
- Elements with an equal key keep their original order
- Sorting never fails with an error
- The result is always the same for any key
- A list cannot be sorted twice
A results table
Write a function rank(players): the input is a list of (name, score) pairs, the output is a list of names by descending score. With equal scores the names go alphabetically.