ordering
list.sort
Sorts the list in place using the stable Timsort algorithm; returns None. Elements must be pairwise comparable unless a key function reduces them to a comparable value.
list.sort(*, key=None, reverse=False) Parameters
| Parameter | Purpose |
|---|---|
| key | Callable applied to each element to derive a sort key (e.g. key=str.lower). |
| reverse | If True, sorts in descending order (stability is preserved). |
Examples
>>> lst = [3, 1, 2]
>>> lst.sort()
>>> lst
[1, 2, 3] Sorts in place; returns None.
>>> words = ['Banana', 'apple', 'cherry']
>>> words.sort(key=str.lower)
>>> words
['apple', 'Banana', 'cherry'] Case-insensitive via key function.
>>> lst = [3, 1, 2]
>>> lst.sort(reverse=True)
>>> lst
[3, 2, 1] Descending order.
>>> [1, 'a'].sort()
TypeError: '<' not supported between instances of 'str' and 'int' Mixed uncomparable types raise TypeError.
Gotcha
sort() returns None — writing `lst = lst.sort()` erases the list. In Python 3, mixed-type comparisons (e.g. int vs str) raise TypeError. Sort is stable: equal keys keep their original order.
Related methods
sorted (built-in)
Built-in function that returns a NEW sorted list from any iterable, leaving the source untouched. Uses the same stable Timsort and key/reverse arguments as list.sort.
list.reverse
Reverses the elements of the list in place. Returns None; O(n) time and O(1) extra space.
list[i] / list[i:j:k]
Subscript syntax to read a single element (by index) or a new list (by slice). Slicing always returns a new shallow copy; out-of-range slice bounds are silently clamped while single-index access raises IndexError.
← All Python list methods · Dict methods · list vs tuple vs set