Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Built-in Functions

Python sorted() function

Reference for Python sorted(): return a new sorted list from any iterable, key functions, reverse, stability, mixed types and how it differs from list.sort().

The built-in sorted() function takes any iterable and returns a new list with its items in ascending order. The original is untouched. Because it accepts any iterable, you can sort tuples, sets, dictionary keys, generators and strings with the same call.

Customize the order with key, a function that computes a sort value for each item, and reverse=True for descending order. The sort is stable: items that compare equal keep their original relative order.

Python
sorted([3, 1, 2])                  # [1, 2, 3]
sorted(["b", "A", "c"], key=str.lower)   # ['A', 'b', 'c']

Try it

Python Sorting basics

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Key functions, stability and errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
sorted(iterable, /, *, key=None, reverse=False)
Name Description
iterable Any iterable of comparable items.
key Optional one-argument function. Each item is replaced by key(item) for comparison only.
reverse If True, sort in descending order (still stable).

Return value: a new list.

Raises: TypeError if items cannot be compared (such as int and str), or if key and reverse are passed positionally.

Usage notes

  • sorted() vs list.sort(). sorted() returns a new list from any iterable; list.sort() sorts a list in place and returns None. A common bug is items = items.sort(), which sets items to None.
  • key and reverse are keyword-only. Passing a comparison function as a second argument fails; wrap an old two-argument comparison with functools.cmp_to_key().
  • Stable. Sort by several criteria in steps (secondary key first), or return a tuple from key. Negate numbers in the tuple for mixed ascending/descending order.
  • Strings sort by code point, so uppercase letters come before lowercase ones. Use key=str.casefold for case-insensitive order; locale-aware order needs locale.strxfrm.
  • Mixed types such as numbers and strings raise TypeError. Convert with key.
  • Sets and dicts. A set has no order, so sorted() is the way to print it deterministically. Sorting a dict gives a list of its keys; use sorted(d.items()) for pairs.
  • NaN breaks ordering; the result is unpredictable when floats include nan.
  • Cost. Timsort runs in O(n log n) and is very fast on partially ordered data. The key function is called once per item.
  • Need only a few? heapq.nsmallest() / nlargest() or min() / max() avoid sorting everything.