sorted and key Functions
Scenario: Incidents must be ordered by severity rather than alphabetically.
New words, in plain English
- key function - a function returning the comparison value for each item
- Stable sort - equal-key items keep their original order
- Callable - anything that can be called with parentheses
sorted returns a new list; .sort() changes a list. Pass key= to explain what matters and reverse=True for descending order.
Analogy: A Python program is like a clear set of instructions for a careful helper: names label things, indentation groups steps, and errors explain where the helper became confused.
A small, real example
events = [{"name": "disk", "severity": 3}, {"name": "cpu", "severity": 1}]
ordered = sorted(events, key=lambda event: event["severity"], reverse=True)
Tip: Useoperator.itemgetterorattrgetterwhen it makes a repeated key clearer.
Goal: Practice this idea in the py-list-comprehension challenge at/labs/python. Fix the broken program, run it yourself, then usecheckto prove the real end state.