Built-in function

sorted()

Returns a new sorted list from any collection, smallest first or reversed, with a key function to sort by length, by a field or ignoring case.

BeginnerEvery example below runs in your browser. Change the code and press Run.

sorted(iterable, /, *, key=None, reverse=False)

sorted() takes any collection, a list, tuple, set, string or dictionary, and gives back a new list with the items in order. The original stays as it was.

Two keyword arguments do most of the work. reverse=True sorts from largest to smallest. key is a function that turns each item into the value to sort by: key=len sorts words by length, key=str.lower ignores capital letters, and key=lambda p: p[1] sorts pairs by their second item.

The sort is stable: items that compare equal keep their original order. That lets you sort by several things in steps. One surprise for beginners: the list method items.sort() sorts in place and returns None, while sorted(items) returns the new list.

Parameters

ParameterWhat it is
iterable
required
Anything you can loop over. A dictionary gives its keys; a string gives its characters.
key
optional, default None
A function of one argument. Items are ordered by what it returns. Must be given by name.
reverse
optional, default False
Set to True to sort from largest to smallest. Must be given by name.

Return value

A new list with the items in sorted order.

Examples

1Sort numbers and words

Pythoneditable
print(sorted([42, 7, 19, 3]))
print(sorted([42, 7, 19, 3], reverse=True))
print(sorted(["pear", "apple", "fig"]))
print(sorted("python"))
Output
[3, 7, 19, 42]
[42, 19, 7, 3]
['apple', 'fig', 'pear']
['h', 'n', 'o', 'p', 't', 'y']

2Sort with a key

Pythoneditable
cities = ["Rome", "amsterdam", "Lima", "oslo"]
print(sorted(cities))
print(sorted(cities, key=str.lower))
print(sorted(cities, key=len))
Output
['Lima', 'Rome', 'amsterdam', 'oslo']
['amsterdam', 'Lima', 'oslo', 'Rome']
['Rome', 'Lima', 'oslo', 'amsterdam']

Without a key, all capitals come before all small letters. With key=len, Rome, Lima and oslo tie at 4 letters and keep their original order.

3Sort a dictionary by its values

Pythoneditable
sales = {"Ana": 340, "Ben": 520, "Chen": 410}
ranking = sorted(sales.items(), key=lambda kv: kv[1], reverse=True)
for place, (name, amount) in enumerate(ranking, start=1):
    print(place, name, amount)
Output
1 Ben 520
2 Chen 410
3 Ana 340

4Sort by two things

Return a tuple from the key: Python compares the first part, then the second when the first ties.

Pythoneditable
people = [("Lena", 31), ("Omar", 25), ("Ana", 31), ("Yuki", 25)]
for name, age in sorted(people, key=lambda p: (-p[1], p[0])):
    print(age, name)
Output
31 Ana
31 Lena
25 Omar
25 Yuki

-p[1] puts the oldest first; names then go A to Z within each age.

5Show a set in a fixed order

Pythoneditable
tags = set(["travel", "food", "art", "food"])
print(sorted(tags))
Output
['art', 'food', 'travel']

Sets have no order of their own, so sorting them is the reliable way to print or compare them.

Common mistakes

Using the result of list.sort()

list.sort() changes the list and returns None. Use sorted() when you want a new list back.

Pythoneditable
nums = [3, 1, 2]
result = nums.sort()
print(result)
print(nums)
print(sorted([3, 1, 2]))
Output
None
[1, 2, 3]
[1, 2, 3]

Sorting numbers stored as text

Strings sort character by character, so "100" comes before "9". Use key=int or key=float.

Pythoneditable
sizes = ["9", "100", "25"]
print(sorted(sizes))
print(sorted(sizes, key=int))
Output
['100', '25', '9']
['9', '25', '100']

Mixing types

Python will not compare a number with a string, so sorting a list that holds both raises TypeError. Convert everything to one type first, or use a key such as key=str.

Pythoneditable
mixed = [3, "2", 1]
try:
    sorted(mixed)
except TypeError:
    print("TypeError: cannot compare str and int")
print(sorted(mixed, key=int))
Output
TypeError: cannot compare str and int
[1, '2', 3]

Questions people ask

What is the difference between sort() and sorted() in Python?

items.sort() changes the list itself and only works on lists. sorted(items) works on any collection and returns a new list.

How do I sort a list in descending order?

sorted(items, reverse=True).

How do I sort a list of dictionaries by a field?

sorted(rows, key=lambda r: r["price"]), or with from operator import itemgetter: key=itemgetter("price").

How do I sort strings alphabetically ignoring case?

sorted(words, key=str.lower).

Spotted a mistake on this page? Tell us