Python 3 reference · List Methods

Python List sort() Method

Sort the list in place, optionally by a key function and in reverse. Returns None; sorted() returns a new list.

Python 3 Since 3.0

Syntax

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

Parameters

ParameterDescription
key optional A function returning the value to sort by. Default: None
reverse optional Sort from largest to smallest. Default: False

Return value

None.

Examples

Sort numbersTry it yourself
scores = [70, 95, 82]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)

Output

[70, 82, 95]
[95, 82, 70]
Sort with a keyTry it yourself
words = ["banana", "Apple", "cherry"]
words.sort(key=str.lower)
print(words)
words.sort(key=len)
print(words)

Output

['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
Sort records, or use sorted()Try it yourself
people = [("Ada", 36), ("Linus", 28)]
people.sort(key=lambda p: p[1])
print(people)
new = sorted(people, reverse=True)  # copy instead
print(new)

Output

[('Linus', 28), ('Ada', 36)]
[('Linus', 28), ('Ada', 36)]

Common mistakes

items = items.sort() sets items to None. Call items.sort() on its own line, or use sorted(items). Python's sort is stable: equal items keep their original order.

Version history

VersionChange
Python 3.0Added