Lesson explanation
After this lesson, you will be able to:
key parameter of sorted().str.lower and len.You already know that sorted(values) creates a sorted list and list.sort() changes an existing list. Python's key= makes sorting more flexible: the key function receives each item and returns the value Python compares.
sorted(names, key=str.lower)For longer strings, key=len orders by length. Note that str.lower and len are passed as functions—no parentheses after their names.
When sorting records, write a small named function that takes a record and returns its ranking key. You may return a tuple like (priority, name) to break ties: Python compares the first element, then the next when necessary.
Python sorting is stable: if two items have equal keys, they keep their original relative order. reverse=True reverses the key ordering; it does not solve every mixed ascending/descending requirement by itself. Use carefully chosen keys for those cases.
labels = ["Worker", "api", "Cache"]
ordered = sorted(labels, key=str.lower)
print(ordered)Output:
['api', 'Cache', 'Worker']The original capitalization is preserved; only comparisons use lowercase.
routes = ["/health", "/", "/api"]
print(sorted(routes, key=len))Output:
['/', '/api', '/health']len is passed as the key function, not called once before sorting.
jobs = [
{"name": "backup", "duration": 40},
{"name": "sync", "duration": 10},
]
def duration_key(job):
return job["duration"]
ordered = sorted(jobs, key=duration_key)
print([job["name"] for job in ordered])Output:
['sync', 'backup']The key function is applied to each record.
alerts = [
{"team": "Zulu", "level": 2},
{"team": "alpha", "level": 1},
{"team": "Beta", "level": 2},
]
def alert_key(alert):
return (alert["level"], alert["team"].lower())
print([item["team"] for item in sorted(alerts, key=alert_key)])Output:
['alpha', 'Beta', 'Zulu']The numeric level comes first; lowercase team names break ties alphabetically.
| Goal | Technique |
|---|---|
| Case-insensitive text order | sorted(items, key=str.lower) |
| Order by length | sorted(items, key=len) |
| Sort dictionaries by a field | sorted(records, key=named_function) |
| Break ties | Return a tuple from the key function |
| Preserve the input list | Use sorted() instead of .sort() |
key=str.lower, not key=str.lower(); the latter calls a function without the item.list.sort() mutates the list and returns None; sorted() returns a new list.lambda just to sort a few records—named functions work well and remain readable.