ordering

sorted (built-in)

Built-in function that returns a NEW sorted list from any iterable, leaving the source untouched. Uses the same stable Timsort and key/reverse arguments as list.sort.

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

Parameters

Parameter Purpose
iterable Any iterable — list, tuple, set, dict (keys), generator.
key Function producing the sort key per element.
reverse If True, descending order.

Examples

>>> nums = (3, 1, 2)
>>> sorted(nums)
[1, 2, 3]
>>> nums
(3, 1, 2)

Original tuple is unchanged; result is always a list.

>>> sorted('bca')
['a', 'b', 'c']

Any iterable is accepted; strings become lists of chars.

>>> people = [{'age': 30}, {'age': 20}]
>>> sorted(people, key=lambda p: p['age'])
[{'age': 20}, {'age': 30}]

key extracts the comparable value.

>>> sorted({'b': 2, 'a': 1})
['a', 'b']

Sorting a dict sorts its keys.

Gotcha

sorted() always returns a list, even from a tuple or set — check your caller if you expected the source type. Use list.sort when you already own a list and want in-place efficiency.

Related methods

← All Python list methods · Dict methods · list vs tuple vs set