sorted
Sort the items of any iterable.
Python 3.13
sorted(iterable, *, key=None, reverse=False)- =default value
- *arguments after it by name only
- iterable
- The items to sort.Iterable
- key
- A function whose result is used to compare items, such as len or str.lower; without it, the items themselves are compared.Callable | NoneOptional
- reverse
- If True, sorts in descending order.boolOptional
Return value
A new sorted list; the original object is not changed.
Examples
Sorting in ascending order
Python 3.13
print(sorted([3, 1, 4, 1, 5, 9]))[1, 1, 3, 4, 5, 9]
Sorting by length in reverse order
Python 3.13
print(sorted(['kiwi', 'banana', 'apple'], key=len, reverse=True))['banana', 'apple', 'kiwi']
Details
The sort is stable: items with equal keys keep their original order. Items must be comparable with each other; a mix of numbers and strings raises TypeError.
