Python sorted() Function: Syntax and 5 Examples

If you have a list in Python and you want it in order, the Python sorted function is the quickest way to get it. It takes any iterable and gives you back a new sorted list, leaving the original untouched.

print(sorted([3, 1, 2]))
# [1, 2, 3]

In this tutorial, I’ll show you its syntax and five examples: numbers and strings, descending order, custom keys, dictionaries and multiple sort keys. I ran every one in Python 3.12.5 in VS Code.

Python sorted() Syntax

sorted(iterable, /, *, key=None, reverse=False)
ParameterRequiredDefaultDescription
iterableYesnoneList, tuple, set, string, dict or generator
keyNoNoneOne-argument function that returns the sort value
reverseNoFalseTrue sorts in descending order

Return value: a new list, always, whatever type you pass in. The / and * mean key and reverse must be passed by name.

Note: Python’s sort is stable, so equal items keep their original order. For the algorithm behind it, see which sorting algorithm Python uses.

When to Use sorted() in Python

  • Ranking scores or prices but keeping the source list
  • Sorting tuples, sets, strings or dictionary keys
  • Ordering records by one or more fields

Working with arrays as well? My sorting arrays and lists in Python tutorial covers both.

Example 1: Sort a List of Numbers or Strings with sorted()

Let me start with a list of test scores and a set of US cities:

scores = [88, 72, 95, 61, 79]
ranked = sorted(scores)

print(ranked)
print(scores)
print(sorted({"Denver", "Austin", "Boston"}))

Output:

[61, 72, 79, 88, 95]
[88, 72, 95, 61, 79]
['Austin', 'Boston', 'Denver']
Python sorted function sorting a list of numbers and strings in VS Code
The original scores list keeps its order.

How does this work? sorted() built a new list, so scores kept its order. The set came back as an alphabetical list, like in sorting a list alphabetically.

Example 2: Sort a List in Descending Order with sorted()

Pass reverse=True to list invoice amounts from biggest to smallest:

invoices = [1249.50, 89.99, 4300.00, 615.25]

for amount in sorted(invoices, reverse=True):
    print(f"${amount:>9,.2f}")

Output:

$ 4,300.00
$ 1,249.50
$   615.25
$    89.99

How does this work? the amounts came back largest first, and the f-string right-aligns them.

Example 3: How Do You Sort with a key Function in Python?

Uppercase letters sort before lowercase. A key function fixes that:

cities = ["seattle", "Austin", "chicago", "Miami"]

print(sorted(cities))
print(sorted(cities, key=str.lower))
print(sorted(cities, key=len))

Output:

['Austin', 'Miami', 'chicago', 'seattle']
['Austin', 'chicago', 'Miami', 'seattle']
['Miami', 'Austin', 'seattle', 'chicago']
Python sorted with key=str.lower and key=len on a list of US cities in VS Code
Three orders for the same four cities.

How does this work? capitals came first in the plain sort. key=str.lower compared lowercase copies, and key=len sorted by length.

Example 4: Sort a Dictionary by Value with sorted()

sorted() on a dictionary returns its keys. Sort .items() to rank states by sales:

sales = {"Texas": 18450, "Ohio": 9320, "California": 24780}

print(sorted(sales))
top = sorted(sales.items(), key=lambda kv: kv[1], reverse=True)
for state, total in top:
    print(f"{state:<11}${total:,}")

Output:

['California', 'Ohio', 'Texas']
California $24,780
Texas      $18,450
Ohio       $9,320
Python sorted dictionary items by value with a lambda key in descending order
Keys, then states ranked by sales.

How does this work? the lambda picks the total from each (state, total) tuple. More options: sorting a dictionary by value.

Example 5: Sort a List of Dictionaries by Multiple Keys

Return a tuple from key to sort by state, then by total from high to low:

orders = [
    {"id": 1043, "state": "TX", "total": 89.99},
    {"id": 1044, "state": "CA", "total": 249.00},
    {"id": 1045, "state": "TX", "total": 310.50},
    {"id": 1046, "state": "CA", "total": 55.25},
]

by_state = sorted(orders, key=lambda o: (o["state"], -o["total"]))
for o in by_state:
    print(o["state"], o["id"], f"${o['total']:.2f}")

Output:

CA 1044 $249.00
CA 1046 $55.25
TX 1045 $310.50
TX 1043 $89.99
Python sorted list of order dictionaries by state and total with a tuple key
CA first, biggest order on top in each state.

How does this work? Python compares the tuples field by field, and the minus sign flips the total. For classes, read sorting a list of objects by attribute.

sorted() vs list.sort() in Python

Featuresorted()list.sort()
Works onAny iterableLists only
ReturnsA new listNone
Original dataUnchangedChanged in place

Pick sorted() to keep the original or sort a non-list; pick list.sort() for big lists. For a pandas DataFrame, you’d use sort_values() in pandas.

Common Mistakes with Python sorted()

Here are the errors I see most often with Python sorting:

try:
    sorted([3, "10", 7])
except TypeError as err:
    print("1. TypeError:", err)

try:
    sorted([12, 4, 9], len)
except TypeError as err:
    print("2. TypeError:", err)

nums = [12, 4, 9]
print("3.", nums.sort())

Output:

1. TypeError: '<' not supported between instances of 'str' and 'int'
2. TypeError: sorted expected 1 argument, got 2
3. None
Common Python sorted errors: mixed types, positional key, sort() returning None
Two TypeErrors and one silent None.
  1. Mixed types like str and int can’t be compared.
  2. key is keyword-only, so sorted(nums, len) fails.
  3. list.sort() returns None; don’t assign its result.

Wrapping Up the Python sorted() Function

Python’s sorted() function returns a new, stable, sorted list from any iterable, and key plus reverse cover nearly every custom order.

To see sorting done by hand, try sorting a list without sort(), then browse more Python built-in functions and methods.

You’ll find more sorting practice here:

Python sorted() Function Questions, Answered

Does sorted() change the original list?

No. It returns a new list; the original keeps its order.

Is Python sorted() stable?

Yes. Items with equal keys keep their original order, so you can sort in several passes.

What sorting algorithm does sorted() use?

CPython uses Timsort, a hybrid of merge sort and insertion sort.

Can sorted() take a generator?

Yes. It consumes any iterable, including generators, and returns a list.

How do I use an old cmp function with sorted()?

Wrap it with functools.cmp_to_key() and pass the result as key. See sorted() in the Python docs.