Chapters
Python114 chapters

ReferenceBuilt-in functions

sorted()

A new sorted list, leaving the original alone.

Signature

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

Parameters

NameMeans
iterableanything you can walk
keycalled on each item to decide the ordering
reverselargest first when True

Returns

A new list, always, even from a tuple or set.

Example

Python
print(sorted([3, 1, 2]))
print(sorted(["banana", "Apple"], key=str.lower))
print(sorted([("a", 2), ("b", 1)], key=lambda p: p[1]))

Output

[1, 2, 3]
['Apple', 'banana']
[('b', 1), ('a', 2)]

See also