Python theorytheory 0/50 · 0%
Functions · medium

30. Sorting and key functions

sorted(), .sort(), and custom comparison keys.

`sorted(iterable)` returns a new sorted list; `list.sort()` sorts in place. Both accept a `key` function and a `reverse` flag.

python
txs = [{"amount": 5}, {"amount": 1}, {"amount": 3}]
sorted(txs, key=lambda t: t["amount"])
sorted(txs, key=lambda t: t["amount"], reverse=True)

from operator import itemgetter
sorted(txs, key=itemgetter("amount"))

Python's sort is stable — elements that compare equal keep their relative order — which matters when sorting by multiple criteria in sequence (sort by the least significant key first).

Check your understanding

  1. 1. What is the difference between `sorted(x)` and `x.sort()`?

  2. 2. What does 'stable sort' guarantee?

  3. 3. What does `key=itemgetter("amount")` do?