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.
sorted([3, 1, 2]) # [1, 2, 3] sorted(["b", "A", "c"], key=str.lower) # ['A', 'b', 'c']
Try it
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.
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
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()vslist.sort().sorted()returns a new list from any iterable;list.sort()sorts a list in place and returnsNone. A common bug isitems = items.sort(), which setsitemstoNone.keyandreverseare keyword-only. Passing a comparison function as a second argument fails; wrap an old two-argument comparison withfunctools.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.casefoldfor case-insensitive order; locale-aware order needslocale.strxfrm. - Mixed types such as numbers and strings raise
TypeError. Convert withkey. - 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; usesorted(d.items())for pairs. NaNbreaks ordering; the result is unpredictable when floats includenan.- Cost. Timsort runs in O(n log n) and is very fast on partially ordered data. The
keyfunction is called once per item. - Need only a few?
heapq.nsmallest()/nlargest()ormin()/max()avoid sorting everything.
Related
min(),max(),reversed(),sum(),list()- Lessons: List methods, Higher-order functions, Algorithms