list.sort()
Puts the items of a list in order, smallest first by default. It changes the list itself and returns None.
list.sort(*, key=None, reverse=False)sort() rearranges the items of a list into order: numbers from small to large, strings alphabetically. Add reverse=True for the other direction, or key= to sort by something other than the items themselves, such as their length or a field.
The biggest surprise: sort() changes the list and returns None. Writing items = items.sort() loses your list. If you want a sorted copy and keep the original, use the built-in sorted(), which also works on tuples, strings and dictionaries.
Strings are compared character by character using their code numbers, so every capital letter comes before every lower-case letter: "Zoe" sorts before "adam". Use key=str.lower to ignore case.
Parameters
| Parameter | What it is |
|---|---|
keyoptional, default None | A function called once on each item; the list is sorted by what it returns. For example key=len or key=str.lower. Must be passed by name. |
reverseoptional, default False | True sorts from largest to smallest. Must be passed by name. |
Return value
Nothing (None). The list is changed in place.
Examples
1Sort numbers and words
prices = [19.99, 4.5, 12.0, 7.25]
prices.sort()
print(prices)
cities = ["Oslo", "Lima", "Cairo", "Bern"]
cities.sort()
print(cities)[4.5, 7.25, 12.0, 19.99] ['Bern', 'Cairo', 'Lima', 'Oslo']
2Largest first with reverse=True
scores = [72, 95, 88, 60]
scores.sort(reverse=True)
print(scores)
print("Top 3:", scores[:3])[95, 88, 72, 60] Top 3: [95, 88, 72]
3sort() vs sorted()
nums = [3, 1, 2]
result = nums.sort()
print(result)
print(nums)
nums = [3, 1, 2]
new = sorted(nums)
print(new)
print(nums)None [1, 2, 3] [1, 2, 3] [3, 1, 2]
sort() changes the list and returns None. sorted() returns a new list and leaves the original alone.
4Sort by a key: ignore case, or by length
names = ["zoe", "Adam", "bella", "Chris"]
names.sort()
print(names)
names.sort(key=str.lower)
print(names)
names.sort(key=len)
print(names)['Adam', 'Chris', 'bella', 'zoe'] ['Adam', 'bella', 'Chris', 'zoe'] ['zoe', 'Adam', 'bella', 'Chris']
Sorting is stable: items with the same key keep their previous order. "bella" and "Chris" both have 5 letters, so they stay in the order the previous sort left them.
5Sort records by a field
A list of (name, age) pairs, sorted by age and then by name:
people = [("Lena", 34), ("Omar", 28), ("Ines", 34), ("Yuki", 22)]
people.sort(key=lambda p: (p[1], p[0]))
for name, age in people:
print(age, name)22 Yuki 28 Omar 34 Ines 34 Lena
Common mistakes
Assigning the result of sort()
sort() returns None, so the variable loses the list. Call sort() on its own line, or use sorted() if you want a value back.
ages = [40, 18, 25]
ages = ages.sort()
print(ages)
ages = sorted([40, 18, 25])
print(ages)None [18, 25, 40]
Sorting a list that mixes numbers and text
Python 3 cannot compare 3 and "10", so sort() raises a TypeError. Make all items the same type first.
values = [3, "10", 7]
try:
values.sort()
except TypeError:
print("TypeError: cannot compare text with numbers")
values = sorted(int(v) for v in values)
print(values)TypeError: cannot compare text with numbers [3, 7, 10]
Numbers stored as text sort like words
"100" comes before "9" because "1" comes before "9". Sort with key=int.
sizes = ["9", "100", "20"]
sizes.sort()
print(sizes)
sizes.sort(key=int)
print(sizes)['100', '20', '9'] ['9', '20', '100']
Questions people ask
What is the difference between sort() and sorted() in Python?
list.sort() changes the list in place and returns None; it only exists on lists. sorted() works on any iterable and returns a new list, leaving the original unchanged.
How do I sort a list in descending order?
items.sort(reverse=True), or sorted(items, reverse=True) for a new list.
How do I sort a list of dictionaries by a key?
people.sort(key=lambda p: p["age"]). The key function picks the value to sort by.
How do I sort strings without caring about upper and lower case?
Use key=str.lower. For international text, key=str.casefold is a little more thorough.