Python 3 reference · Built-in Functions

Python sorted() Function

Return a new sorted list from any iterable. Supports a key function and reverse order; the original is left unchanged.

Python 3 Since 3.0

Syntax

sorted(iterable, /, *, key=None, reverse=False)

Parameters

ParameterDescription
iterable The items to sort.
key optional A function that returns the value to sort by. Default: None
reverse optional Sort from largest to smallest. Default: False

Return value

A new list.

Examples

Basic sortingTry it yourself
print(sorted([3, 1, 2]))
print(sorted("python"))
print(sorted([3, 1, 2], reverse=True))

Output

[1, 2, 3]
['h', 'n', 'o', 'p', 't', 'y']
[3, 2, 1]
Sort by a keyTry it yourself
words = ["banana", "Apple", "cherry"]
print(sorted(words))                  # uppercase sorts first
print(sorted(words, key=str.lower))   # case-insensitive
print(sorted(words, key=len))

Output

['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
['Apple', 'banana', 'cherry']
Sort by several fieldsTry it yourself
people = [("Ada", 36), ("Linus", 28), ("Grace", 36)]
print(sorted(people, key=lambda p: (-p[1], p[0])))

Output

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

sorted() vs list.sort()

sorted(x) returns a new list and works on any iterable; my_list.sort() sorts the list in place and returns None. Python's sort is stable: items with equal keys keep their original order.

Version history

VersionChange
Python 3.0Added