list.sort()
Reorder the list in place using Python's stable Timsort. Returns None on purpose — the API pushes you toward `sorted()` when you want a new list.
Demo
The demo shows the LIST STATE after sorting. Python actually returns None; the meaningful effect is mutation. Sort is stable — equal items keep their original relative order. The demo input arrives as strings, so numeric cases sort lexicographically ("10" < "2") unless you convert first — a classic footgun documented in the pitfalls.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| key | callable | no (None) | Function of one argument used to extract a comparison key from each item. Keyword-only. |
| reverse | bool | no (False) | If True, sort descending. Stability is preserved either way. Keyword-only. |
Return value
None — Returns None — the useful effect is mutation. The demo shows the list state after sorting.
Common patterns
people.sort(key=lambda p: p.age)
rows.sort(key=lambda r: (r.dept, -r.salary))
names.sort(key=str.lower)
Examples
Pitfalls
xs = [3, 1, 2] xs = xs.sort() print(xs)
xs.sort() # mutate, keep name # or xs = sorted(xs) # new list, replace name
(3, 1, 2).sort()
sorted((3, 1, 2))
xs = ["10", "2", "1"] xs.sort() xs
xs = ["10", "2", "1"] xs.sort(key=int) xs
xs = [1, "a", 2] xs.sort()
xs.sort(key=str) # coerce for comparison
When to use
- The original list order is not needed — save the allocation
- Sorting is followed by more mutations on the same list
- Very large lists where duplicating memory would hurt
- You need to keep the original order → sorted() copy
- Sorting an iterable that is not a list → sorted()
- One-liner in a chain (sort returns None, breaks the chain)
- Concurrent reads of the list while sorting
Notes
FAQ
It is a design signal — Python returns None from mutating methods to discourage the misleading `xs = xs.sort()` pattern and to remind callers that a copy would need `sorted()`.