sorted()

Return a new sorted list from any iterable — the input stays untouched.

Built-in functionPython 2.4+Live demo
Common call
sorted(names)
Returns
always a NEW list, whatever iterable went in
Replaces
list.sort() sorts in place and returns None; sorted never mutates
Watch out
mixed incomparable types (int vs str) raise TypeError
sorted(iterableiterableAnything iterable: list, tuple, string, dict (its keys), generator.type: iterable · required, keykeyOne-argument function computing the sort key per item, e.g. key=len or key=str.lower.type: callable · default: None=None, reversereverseTrue sorts descending.type: bool · default: False=False)
list

Demo

Live evaluation
Try:
Inputs
itemslistcomma-separated items
Output
['banana', 'apple', 'cherry'].sorted()
['apple', 'banana', 'cherry']

The demo’s comma-separated items are strings, so they sort lexicographically — exactly why ’10’ comes before ’2’, and uppercase before lowercase (code-point order). Convert to numbers, or pass key=int / key=str.lower, when that is not what you want.

Parameters

NameTypeRequiredDescription
iterableiterableyesAnything iterable: list, tuple, string, dict (its keys), generator.
keycallableno (None)One-argument function computing the sort key per item, e.g. key=len or key=str.lower.
reverseboolno (False)True sorts descending.

Return value

listA NEW sorted list. The input iterable is never modified — unlike list.sort().

Common patterns

Sort by a computed key
The key function runs once per item.
sorted(words, key=len)
sorted(users, key=lambda u: u.age)
Case-insensitive sort
Lowercase as the key, original strings in the result.
sorted(names, key=str.lower)
Sort a dict by value
Sort the items, then rebuild.
dict(sorted(d.items(), key=lambda kv: kv[1], reverse=True))
Numeric sort of digit strings
key=int fixes the classic ’10 before 2” problem.
sorted(["10", "2", "1"], key=int)
# ['1', '2', '10']

Examples

1. Sort strings
sorted(["b", "a", "c"])
Returns
['a', 'b', 'c']
2. Digit strings sort as text
sorted(["10", "2", "1"])
Returns
['1', '10', '2']
3. Descending
sorted([3, 1, 2], reverse=True)
Returns
[3, 2, 1]
4. Any iterable in, list out
sorted("cab")
Returns
['a', 'b', 'c']

Pitfalls

1. Digit strings sort lexicographically
Strings compare character by character — "10" < "2" because "1" < "2".
Surprising
sorted(["10", "2", "1"])
['1', '10', '2']
Fix
sorted(["10", "2", "1"], key=int)
['1', '2', '10']
2. sorted vs list.sort confusion
list.sort() returns None — assigning it loses the list.
Wrong
lst = lst.sort()
lst is None
Fix
lst = sorted(lst)  # or: lst.sort()
sorted list
3. Uppercase sorts before lowercase
Default order is by Unicode code point: all A–Z precede a–z.
Surprising
sorted(["b", "A"])
['A', 'b']
Fix
sorted(["b", "A"], key=str.lower)
['A', 'b'] — case-insensitive
4. Mixed types raise
Python 3 refuses to compare unrelated types.
Raises
sorted([3, "1", 2])
TypeError: '<' not supported between instances of 'str' and 'int'
Normalize first
sorted([3, "1", 2], key=int)
['1', 2, 3]

When to use

Use it
  • You need the original order preserved elsewhere
  • Sorting non-list iterables (tuples, generators, dict items)
  • Chaining: sorted(...) feeds the next expression directly
Reach for something else
  • Huge list, original order not needed → list.sort() (saves a copy)
  • Only the top-k items → heapq.nlargest / nsmallest
  • Repeatedly inserting into sorted order → bisect.insort

Notes

Complexity
O(n log n) — Timsort; O(n) on already-sorted runs
Return
always a new list; stable sort (equal items keep order)
CPython impl
Python/bltinmodule.c :: builtin_sorted
Memory
O(n) for the new list
Thread-safe
Yes for the copy; the source should not mutate concurrently

FAQ

sorted works on any iterable and returns a new list; list.sort exists only on lists, sorts in place, and returns None. Same algorithm, same key/reverse options.

History

3.0
The cmp parameter removed — key functions only.
2.4
sorted() introduced.