list.sort()
Python · Lists
Theory
.sort() rearranges the items of a list in place into ascending order and returns None. sales = [300, 100, 250] then sales.sort(reverse=True) gives [300, 250, 100]. Numbers sort by value and strings sort by character code, so uppercase letters come before lowercase ones. A list mixing types that cannot be compared, like [3, 'a'], raises TypeError.
The key argument takes a function that is called once per item, and items are ordered by its result: names.sort(key=len) sorts by length and names.sort(key=str.lower) sorts case-insensitively. Python's sort (Timsort) runs in O(n log n) and is stable, meaning items with equal keys keep their original relative order, which lets you sort by several fields in steps. If you need to keep the original list, use sorted(sales), which returns a new sorted list and works on any iterable.
Why we use it
Ranked output is everywhere: top customers by revenue, latest dates first, names alphabetically. sort() orders data efficiently, and key= lets you sort by any rule without rewriting the data.
When to use it
Use list.sort() when you no longer need the original order and want to save memory. Use sorted() to keep the original, or to sort a tuple, dict keys or other iterables. Never write x = x.sort(); that stores None.
How it works
- Call sales.sort(reverse=True)
- Was a key function given? Yes: Compute key(item) for each item. No: Compare the items themselves.
- Order items by those values (descending because reverse=True)
- Rearrange the same list object in place
- Return None
- print(sales) shows [300, 250, 100]
Syntax
list.sort()
list.sort(reverse=True)Example
sales = [300, 100, 250]
sales.sort(reverse=True)
print(sales)Key points
- Mutates the original list; sorted(list) returns a new sorted list instead
- Returns None, so x = x.sort() loses your list
- key= lets you sort by a custom function, e.g. key=len or key=str.lower
- Stable: equal items keep their original order
- Mixing numbers and strings raises TypeError