list · Python
sort / sorted
Sorts in place (sort) or into a new list (sorted). Guaranteed stable.
list.sort(*, key=None, reverse=False); sorted(iterable, /, *, key=None, reverse=False)
Complexity
| Best case | O(n) for already sorted runs |
|---|---|
| Worst case | O(n log n) |
| Extra space | O(n) worst case for merging (plus O(n) for keys) |
CPython uses Timsort-style adaptive merge sort over natural runs (with the powersort merge policy since 3.11). Stability is a documented guarantee.
Tested example
people = [("Ada", 36), ("Bob", 25), ("Cy", 36)]
people.sort(key=lambda p: p[1]) # stable: Ada stays before Cy
assert people == [("Bob", 25), ("Ada", 36), ("Cy", 36)]
newest = sorted(people, key=lambda p: p[1], reverse=True) # sorted() returns a new list
assert newest[0] == ("Ada", 36)
Parameters
- key
- Function computed once per element; elements are ordered by its result.
- reverse
- Descending order, still stable.
Behaviour
- Returns
- sort: None. sorted: a new list.
- Errors and preconditions
- TypeError if elements cannot be compared with <.
- Changes
- sort reorders the list; sorted leaves the input alone.
- Memory and invalidation
- sorted allocates a new list; key= stores one key per element during the sort.
See it step by step: the Merge sort: split, merge and the auxiliary buffer lesson has an interactive 3D visualizer of the same mechanism.