sorted() (Python)

sorted() returns a new sorted list from any iterable, leaving the original unchanged. You can sort in reverse or by a custom key.

Python

Pass reverse=True to sort from largest to smallest, and a key function to sort by something other than the values themselves, such as length or a tuple field.

Syntax

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

Examples

Python

nums = [3, 1, 2]
print(sorted(nums))
print(sorted(nums, reverse=True))

Output:

[1, 2, 3]
[3, 2, 1]

See also

Back to the Dictionary