How does the `key` argument in `sorted()` and `list.sort()` work, and why is it preferred over a custom comparison function?
Answer
The `key` argument accepts a function that is called once per element to compute a sort key, and the elements are then ordered by comparing those computed keys instead of the elements themselves. This is preferred over old-style comparison functions because it only calls the key function n times instead of comparing pairs O(n log n) times, it composes cleanly with `reverse=True`, and it is easy to read: `sorted(people, key=lambda p: p.age)` clearly sorts by age.
Strong answer includes
- key function computes a sort key once per element
- faster than a pairwise comparison function
- composes with reverse=True and reads clearly
Practical example
sorted(products, key=lambda p: (-p.rating, p.price))sorts by highest rating first, then by lowest price among equally rated products, using a tuple key.