Python Glossary Русский

all Python 3Lists (list)function

list.sort

sorting

Sort the list in place; key= sets a key function, reverse=True descending. For a new sorted list without mutating, use the built-in sorted().

Syntax

lst.sort(*, key=None, reverse=False)

The method sorts in place and returns None, so lst = lst.sort() is the classic mistake that leaves you holding None instead of a list. The sort is stable — items with equal keys keep their original relative order — and the key function is called exactly once per item, with only its results compared, so mixing incomparable types such as numbers and strings raises TypeError; normalise them inside key if you need that.

Examples

lst = [3, 1, 2]
lst.sort()
print(lst)              # → [1, 2, 3]
lst.sort(reverse=True)
print(lst)              # → [3, 2, 1]
words = ['bb', 'a', 'ccc']
words.sort(key=len)
print(words)            # → ['a', 'bb', 'ccc']

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy