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
| Parameter | Description |
|---|---|
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
scores = [70, 95, 82]
scores.sort()
print(scores)
scores.sort(reverse=True)
print(scores)
Output
[70, 82, 95] [95, 82, 70]
words = ["banana", "Apple", "cherry"]
words.sort(key=str.lower)
print(words)
words.sort(key=len)
print(words)
Output
['Apple', 'banana', 'cherry'] ['Apple', 'banana', 'cherry']
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
list.reverse()· Reverse the order of the items in place. Returns None; use reversed() or slicing for a reversed copy.sorted()· Return a new sorted list from any iterable. Supports a key function and reverse order; the original is left unchanged.- Python Lists · tutorial