Sorting
Sorting puts a sequence into order. Python's sort and sorted use Timsort, a stable O(n log n) algorithm. You control the order with key and reverse.
Detailed Explanation
sorted(items) returns a new list. items.sort() reorders a list in place and returns None. Both take key= and reverse=. The key function is called once per element; its results are cached and compared. sorted(users, key=lambda u: u["email"]) sorts by email. key=str.lower is a case-insensitive string sort.
Timsort is a hybrid of merge sort and insertion sort. It finds already-ordered runs and merges them. On shuffled data it is O(n log n). On nearly sorted data it is close to O(n). It is stable: equal keys keep their original order. Stability is why you can sort by last name and then by first name with two passes, most-significant last.
Items must be comparable unless you supply a key. Mixing int and str raises TypeError. Mixing None and numbers does too. A key that returns a tuple sorts by the first element, then the second: key=lambda u: (u["role"], u["name"]).
reverse=True flips the result. For a descending numeric key and an ascending tie-breaker, invert the number (key=lambda r: (-r.score, r.name)) rather than reversing the whole sort.
Do not implement quicksort in application code. Use sorted. Implement a sort when you are studying algorithms or when you need a partial order the builtins cannot express. heapq.nsmallest is better than a full sort when you only need the top k.
list.sort only exists on lists. To sort a set or a dict's keys, pass them to sorted. Dicts preserve insertion order; sorted(d) sorts keys into a new list, it does not reorder the dict.
Code Examples
users = [
{"name": "linus", "role": "admin"},
{"name": "ada", "role": "user"},
{"name": "grace", "role": "admin"},
]
print([u["name"] for u in sorted(users, key=lambda u: (u["role"], u["name"]))])
# ['grace', 'linus', 'ada']scores = [9, 1, 4]
print(sorted(scores, reverse=True)) # [9, 4, 1]
scores.sort()
print(scores) # [1, 4, 9]# Stability: two passes, last sort is the primary key.
rows = [("ada", 2), ("linus", 2), ("ada", 1)]
rows = sorted(rows, key=lambda r: r[0])
rows = sorted(rows, key=lambda r: r[1])
print(rows) # [('ada', 1), ('ada', 2), ('linus', 2)]Common Gotchas
`items = items.sort()` sets `items` to `None`
`sort` is in place. Use `sorted` when you want a new list.
Incomparable types
`sorted([1, "a"])` raises `TypeError`. Normalise with a key.
A slow `key` is called n times, not n log n
still, keep it cheap. Precompute if it hits I/O.
`sorted` on a dict yields sorted keys
`sorted(d.items(), key=...)` if you wanted pairs.