Lesson 9: Sorting & custom keys
Picture a shelf of books in no order, and you want to arrange them by height. That's 'sorting', and Python has a ready-made tool — sorted — that does the work. Use key=... to choose what to sort by, and reverse=True to flip the order. Python's sort is 'stable' and costs O(n log n). The real intervie
Sorting is like arranging a deck of cards into order. The key is how you say 'what to sort by' — by number, by color, or first by color and then by number. And reverse=True simply says 'arrange from largest to smallest'.
- sorting
- Arranging a collection into a defined order. Comparison-based sorting takes O(n log n) in the general case.
- sort key
- A function returning, for each item, the value to sort by — e.g. key=lambda x: x[1] sorts by the second element.
- stable sort
- A sort in which items with an equal key keep their original order. Python's sort is stable.