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
list.sort
Sorts the list in place using the stable Timsort algorithm; returns None. Elements must be pairwise comparable unless a key function reduces them to a comparable value.
list.reverse
Reverses the elements of the list in place. Returns None; O(n) time and O(1) extra space.
list.copy
Returns a shallow copy of the list — a new list containing the same element references. Equivalent to lst[:] or list(lst); does not recursively copy nested mutables.
← All Python list methods · Dict methods · list vs tuple vs set