Browse topics

Sorting with sorted and list.sort

Version
3.14
Review
Draft

Summary#

sorted returns a new list from any iterable. list.sort reorders an existing list in place. Both accept key and reverse, and both are stable: items with equal keys keep their relative order.

Syntax#

python
result = sorted(iterable, key=function, reverse=False)
items.sort(key=function, reverse=True)

Example#

python
from operator import itemgetter

rows = [("Linh", 31), ("An", 45), ("Binh", 31)]

by_age_then_name = sorted(rows, key=itemgetter(1, 0))
print([name for name, _ in by_age_then_name])

rows.sort(key=itemgetter(1), reverse=True)
print([name for name, _ in rows])

words = ["beta", "Alpha", "gamma", "Delta"]
print(sorted(words))
print(sorted(words, key=str.casefold))

Expected output#

Text
['Binh', 'Linh', 'An']
['An', 'Linh', 'Binh']
['Alpha', 'Delta', 'beta', 'gamma']
['Alpha', 'beta', 'Delta', 'gamma']

Common mistakes#

items = items.sort() replaces the name with None because list.sort returns nothing. Call it on its own line, or assign the result of sorted. Default string ordering is case-sensitive, so use a key such as str.casefold when case should not matter.

Version applicability#

sorted and list.sort support the shown options on all Python 3 releases. The case-insensitive sort in the example uses str.casefold, which requires Python 3.3 or later.

Sources#

Attribution
DevLookup contributors
License
CC-BY-4.0