Codiqo

Learn Python · lesson 55 of 60 · about 8 minutes

Lambdas and Sorting by Key

Sort lists, and find the biggest or smallest, by any rule you choose.

What you'll learn

  • Sort with sorted() and reverse=True
  • Sort by a rule with key
  • Write tiny functions with lambda

Homework in order

The assistant already keeps Sam's homework as Homework objects, each with a subject and the days until it's due. Now Sam wants it listed in order: by days, so the most urgent comes first, or by subject, whichever Sam types. Objects can't be put in order by themselves, because Python doesn't know which part to compare, so the sort needs a rule.

Sorting by a rule

sorted(items) gives a new list in order, smallest first; reverse=True flips it.

To sort by something else, pass a key: a function that turns each item into the thing to compare. sorted(words, key=len) sorts words by their length.

Different orders

words = ["banana", "fig", "kiwi"]
print(sorted(words))
print(sorted(words, key=len))
print(sorted(words, key=len, reverse=True))

Output

['banana', 'fig', 'kiwi']
['fig', 'kiwi', 'banana']
['banana', 'kiwi', 'fig']

Tiny functions with lambda

When there's no ready-made function for the rule, write a lambda: a one-line function with no name. lambda p: p[1] means "given p, give back p[1]". It works with sorted, max and min alike.

Sorting pairs by score

players = [("Ada", 340), ("Bo", 510), ("Cy", 120)]
print(sorted(players, key=lambda p: p[1]))
print(max(players, key=lambda p: p[1])[0])

Output

[('Cy', 120), ('Ada', 340), ('Bo', 510)]
Bo

A key for objects

A lambda can read an attribute just as easily: sorted(homework, key=lambda piece: piece.days) compares the days of each piece, and key=lambda piece: piece.subject compares the subjects. max(homework, key=lambda piece: piece.days) gives back the whole piece with the most days, so its subject is right there. When two pieces are level, sorted keeps them in the order they were typed, and max gives back the first.

Tip

sorted() never changes the original list; it gives you a new one. list.sort() sorts the list itself, in place, and returns None.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.