all Python 3Built-in functionsterm
sorted
iterators
Returns a new sorted list. Accepts key and reverse. Does not modify the original sequence.
Syntax
sorted(iterable, key=None, reverse=False)
The sort is stable: items with equal keys keep their relative order, which is what makes multi-key sorting work when you sort by the least significant key first. The key function is evaluated exactly once per element, so an expensive key is not a performance trap. Unlike list.sort(), which reorders in place and returns None, sorted accepts any iterable and always hands back a new list.
Examples
print(sorted([3,1,4,1,5])) # → [1,1,3,4,5]
print(sorted('hello')) # → ['e','h','l','l','o']
print(sorted([3,1,2],reverse=True)) # → [3,2,1]
print(sorted(['b','aaa','cc'],key=len)) # → ['b','cc','aaa']
print(sorted({'c':3,'a':1,'b':2})) # → ['a','b','c']
See also
Open in the full glossarydocs.python.orgReport an inaccuracy