Python Sort List: sort() vs sorted(), key, reverse and 9 Tested Examples
To sort a list in Python, call list.sort() to change it in place or sorted() to get a new sorted copy. This guide shows when to use each, how key= and reverse= work, and how to sort by several fields, ignore case, handle None and sort file names naturally.
- Python sort list in one line:
items.sort()changes the list and returnsNone;sorted(items)returns a new list. key=decides what to compare (length, lowercase, a field) andreverse=Trueflips the order.- Python sorting is stable, so you can sort by several fields with a tuple key or with two passes.
- Sorting 100,000 random floats took about 15 ms in our test; an already sorted list took under 1 ms.
Sorting looks trivial until you need to sort names without caring about capitals, order employees by age and then name, or put file2 before file10. This Python sort list guide covers all of it with code we ran on Python 3.13.6; every output shown is copied from that run.
Quick answer
nums = [5, 2, 9, 1]
nums.sort() # in place
print(nums) # [1, 2, 5, 9]
a = [5, 2, 9, 1]
b = sorted(a) # new list
print(b, a) # [1, 2, 5, 9] [5, 2, 9, 1]
Use sort() when you no longer need the original order. Use sorted() when you do, or when the data is not a list at all.
sort() vs sorted(): the real differences
| Feature | list.sort() |
sorted() |
|---|---|---|
| Changes the original | Yes | No |
| Returns | None |
A new list |
| Works on | Lists only | Any iterable: tuple, string, set, dict, generator |
| Memory | No copy | Makes a copy |
key and reverse |
Yes | Yes |
Because sorted() accepts any iterable, it is the one you use for other types. In our run, sorted("banana") gave ['a', 'a', 'a', 'b', 'n', 'n'], sorted({"b": 1, "a": 2}) gave the keys ['a', 'b'], and sorted((3, 1, 2)) returned a list, not a tuple. If you are unsure which container to use, see our list vs tuple vs set guide.
Sort in descending order
nums.sort(reverse=True)
desc = sorted(nums, reverse=True)
reverse=True sorts largest first. It is not the same as list.reverse(), which simply flips the current order without sorting anything.
The key argument
key takes a function that is called once per item; the list is sorted by the results. The items themselves are not changed.
1. Ignore upper and lower case
words = ["banana", "Cherry", "apple"]
print(sorted(words)) # ['Cherry', 'apple', 'banana']
print(sorted(words, key=str.lower)) # ['apple', 'banana', 'Cherry']
Plain sorting compares character codes, and every capital letter comes before every lowercase one, so “Cherry” jumped to the front. key=str.lower compares the lowercase versions.
2. Sort by length
words = ["banana", "Apple", "cherry", "apple"]
print(sorted(words, key=len)) # ['Apple', 'apple', 'banana', 'cherry']
print(sorted(words, key=len, reverse=True)) # ['banana', 'cherry', 'Apple', 'apple']
3. Sort records by a field
from operator import itemgetter
people = [("Asha", 31, "Pune"), ("Ravi", 25, "Delhi"),
("Li", 31, "Delhi"), ("Sam", 25, "Pune")]
print(sorted(people, key=itemgetter(1)))
[('Ravi', 25, 'Delhi'), ('Sam', 25, 'Pune'), ('Asha', 31, 'Pune'), ('Li', 31, 'Delhi')]
itemgetter(1) is a fast, readable alternative to lambda p: p[1]. For objects, attrgetter("age") does the same for attributes. Lambdas are explained in our Python lambda functions guide.
Sort by several fields
4. Tuple key: age descending, then name
print(sorted(people, key=lambda p: (-p[1], p[0])))
[('Asha', 31, 'Pune'), ('Li', 31, 'Delhi'), ('Ravi', 25, 'Delhi'), ('Sam', 25, 'Pune')]
Tuples compare item by item, so the key sorts by the first value and breaks ties with the second. Negating a number reverses just that field.
Stable sorting: the two-pass trick
Python’s sort is stable: items with equal keys keep their existing order. That lets you sort by the secondary field first, then the primary one, which is useful when a field cannot be negated, such as text you want descending.
5. City, then name
s = sorted(people, key=itemgetter(0)) # secondary: name
s = sorted(s, key=itemgetter(2)) # primary: city
print(s)
[('Li', 31, 'Delhi'), ('Ravi', 25, 'Delhi'), ('Asha', 31, 'Pune'), ('Sam', 25, 'Pune')]
Tip: with two passes, each pass can use its own reverse=True. That is the cleanest way to sort, for example, city A to Z but score high to low.
Sort a dictionary by value
6. Items ordered by value
scores = {"x": 3, "y": 1, "z": 2}
print(sorted(scores.items(), key=itemgetter(1))) # [('y', 1), ('z', 2), ('x', 3)]
ranked = dict(sorted(scores.items(), key=itemgetter(1), reverse=True))
Dictionaries keep insertion order, so building a new dict from sorted items gives you a sorted dictionary. Our Python dictionary guide covers more dict patterns.
Tricky data
7. Mixed types fail
sorted([3, "a", 1])
TypeError: '<' not supported between instances of 'str' and 'int'
Python 3 refuses to guess how a number compares with text. Clean or convert the data first.
8. Put None values last
print(sorted([3, None, 1], key=lambda v: (v is None, v))) # [1, 3, None]
The key puts a False or True flag first, so all real values sort before the None values, which are never compared with numbers.
9. Natural sort for file names
files = ["file10", "file2", "file1"]
print(sorted(files)) # ['file1', 'file10', 'file2']
print(sorted(files, key=lambda s: int(s[4:]))) # ['file1', 'file2', 'file10']
Text sorting compares character by character, so “file10” comes before “file2”. Extract the number for the key. For messy real names, use a regular expression to pull out digits; see our Python regex guide.
How fast is Python sorting?
We timed 100,000 random floats, averaging 20 runs:
| Operation | Time per sort |
|---|---|
Copy then list.sort() |
14.8 ms |
sorted(data) |
15.2 ms |
sorted() on already sorted data |
0.9 ms |
Both functions use the same algorithm, so speed is not a reason to choose one over the other. The algorithm detects runs of already ordered data, which is why the presorted list was about 16 times faster. If you only need the top few items, heapq.nlargest(3, data) avoids sorting everything; in our run it returned [9, 7, 5] from [5, 2, 9, 1, 7].
Common mistakes
new = old.sort():sort()returnsNone, sonewisNone. We printed it to confirm. Usesorted(old).- Sorting a tuple or string with
.sort(): those types have nosortmethod. Usesorted(). - Calling the key function: write
key=str.lower, notkey=str.lower(). - Expecting
reverse()to sort: it only flips the order. - Comparing mixed types: clean the data or supply a key that returns comparable values.
Python sort list cheat sheet
| Goal | Code |
|---|---|
| Sort in place | items.sort() |
| New sorted list | sorted(items) |
| Descending | sorted(items, reverse=True) |
| Ignore case | sorted(words, key=str.lower) |
| By field | sorted(rows, key=itemgetter(1)) |
| Two fields, one reversed | key=lambda r: (-r.age, r.name) |
| Dict by value | sorted(d.items(), key=itemgetter(1)) |
| None last | key=lambda v: (v is None, v) |
| Top N only | heapq.nlargest(n, items) |
Sorting objects and dataclasses
Real programs often sort objects rather than tuples. attrgetter reads attributes the way itemgetter reads positions, and it accepts several names for multi-field sorts:
from dataclasses import dataclass
from operator import attrgetter
@dataclass
class Employee:
name: str
dept: str
salary: int
staff = [Employee("Asha", "QA", 90), Employee("Ravi", "Dev", 120),
Employee("Li", "QA", 110), Employee("Sam", "Dev", 120)]
print([e.name for e in sorted(staff, key=attrgetter("salary"), reverse=True)])
print([e.name for e in sorted(staff, key=attrgetter("dept", "name"))])
['Ravi', 'Sam', 'Li', 'Asha']
['Ravi', 'Sam', 'Asha', 'Li']
Ravi and Sam tie on salary, and stability kept them in their original order. If a type has one natural order, let the class define it. A dataclass with order=True compares its fields from left to right:
@dataclass(order=True)
class Version:
major: int
minor: int
patch: int
print(sorted([Version(1, 10, 0), Version(1, 2, 3), Version(1, 2, 0)]))
[Version(major=1, minor=2, patch=0), Version(major=1, minor=2, patch=3), Version(major=1, minor=10, patch=0)]
Version 1.10.0 correctly came last, which plain string sorting of “1.10.0” and “1.2.3” would get wrong. Dataclasses are covered in depth in our Python dataclasses guide.
The same key trick beyond sorting
Once you understand key=, you can use it in several other built-ins that pick items by a rule, often avoiding a full sort:
words = ["banana", "Cherry", "apple", "fig"]
print(max(words, key=len)) # banana
print(min(words, key=len)) # fig
print(min(words, key=str.lower)) # apple
print(heapq.nsmallest(2, words, key=len)) # ['fig', 'apple']
max() and min() scan the list once, which is cheaper than sorting just to take the first item. heapq.nsmallest and nlargest return the top few. itertools.groupby also works with a key, but it only groups neighbouring items, so sort by the same key first; our itertools guide shows the pattern.
Final thoughts
Python sort list tasks come down to two choices: sort() or sorted(), and what to put in key. Pick sorted() when you need the original or have a non-list, use a key function or tuple for anything beyond plain values, and lean on stability for multi-field sorts. For records with many fields, a dataclass with attrgetter keeps sort code readable.
Frequently asked questions
What is the difference between sort() and sorted() in Python?
list.sort() sorts the list in place and returns None. sorted() works on any iterable and returns a new sorted list, leaving the original unchanged.
How do I sort a list in descending order in Python?
Pass reverse=True, as in items.sort(reverse=True) or sorted(items, reverse=True).
How do I sort a list of tuples by the second element?
Use a key: sorted(rows, key=lambda r: r[1]) or the faster sorted(rows, key=itemgetter(1)) from the operator module.
Why does my sorted list print None?
You probably wrote new_list = old_list.sort(). The sort method changes the list in place and returns None; use sorted(old_list) to get a new list.
Is Python sorting stable?
Yes. Items that compare equal keep their original order, which lets you sort by several fields with two passes.
Keep learning
Need help with testing, WordPress or SEO?
We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.