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
| Parameter | Description |
|---|---|
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
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]
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']
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
| Version | Change |
|---|---|
| Python 3.0 | Added |
Related
reversed()· Return an iterator that goes through a sequence backwards, without copying it. Works on lists, tuples, strings and ranges.min()· Return the smallest item in an iterable, or the smallest of several arguments. Supports a key function and a default.max()· Return the largest item in an iterable, or the largest of several arguments. Supports a key function and a default.list()· Create a list: an ordered, changeable sequence. Called with an iterable, it copies its items into a new list.- Python Lists · tutorial
- Python Lambda · tutorial