Python Sorting — sorted, sort, key, and reverse
Almost every program that holds a list sooner or later needs it in order: names alphabetically, scores highest first, rows by one field and then another. Python has two sorting tools that look alike and differ in one place that matters: one builds a new list, the other rearranges the list you hand it. This guide builds the plain form first, then adds a key function, a two-field key, a reversed order, and the stability rule that makes one sort remember an earlier one, with a small working program for each step and the exact output it prints.
Written November 12, 2026 · Tested with Python 3.12.3 · 11 min read
- The main program: a new list, or the same list rearranged
- A key function changes what items compare by
- A tuple key sorts by two fields at once
- reverse flips the finished order
Written November 12, 2026
Tested with Python 3.12.3
What this guide is
Sorting answers one question: in what order should these items stand? The sorted function takes any iterable and returns a new list in order, smallest first. The sort method does the same work inside a list itself. Both compare items with the less-than rule for their type, so numbers stand in numeric order and strings stand in alphabetical order by character code. Two settings change the comparison without changing the tools. The key setting names a function that runs on each item once, and the items compare by what that function returns. The reverse setting flips the finished order. A third fact ties the settings together: a sort in Python is stable, which means items that compare equal keep the order they had before the sort. That one fact is what makes sorting by two fields in two passes work.
The main program: a new list, or the same list rearranged
The two tools differ in where the result lives. The sorted function leaves its input as it was. The sort method changes the list in place and returns None:
nums = [3, 1, 4, 1, 5]
print(sorted(nums))
print(nums)
result = nums.sort()
print(result)
print(nums)
words = ["banana", "apple", "cherry"]
print(sorted(words))
print(sorted("cab"))
The exact output:
[1, 1, 3, 4, 5]
[3, 1, 4, 1, 5]
None
[1, 1, 3, 4, 5]
['apple', 'banana', 'cherry']
['a', 'b', 'c']
The second line is the proof that sorted did not touch its input. The numbers still stand in their first order, ready for a second use. The third line prints None because sort returns nothing. Its work is the change to the list itself, which the fourth line shows. Code that writes nums = nums.sort() throws the sorted list away and stores None in its place, which is the most common sorting bug in Python. Pick sorted when the first order still matters somewhere, or when the source is not a list at all. Pick sort when the list is yours to rearrange and no copy is needed. The last line shows that sorted also takes a string and returns its letters as a list.
A key function changes what items compare by
By default, words compare by their letters, so a short word can stand after a long one. A key function gives each item a stand-in value, and the items compare by the stand-in:
words = ["banana", "fig", "apple", "kiwi"]
print(sorted(words, key=len))
print(sorted(words, key=len, reverse=True))
mixed = ["Banana", "apple", "Cherry"]
print(sorted(mixed))
print(sorted(mixed, key=str.lower))
print(sorted([-3, 1, -2], key=abs))
The exact output:
['fig', 'kiwi', 'apple', 'banana']
['banana', 'apple', 'kiwi', 'fig']
['Banana', 'Cherry', 'apple']
['apple', 'Banana', 'Cherry']
[1, -2, -3]
With len as the key, each word compares by its length, so fig stands first and banana last. The key function runs once per item, not once per comparison, so even a slow key stays cheap. The mixed lines show why case matters. Without a key, capital letters compare before lowercase ones by character code, so both capitalized words stand before apple. With str.lower as the key, each word compares by its lowercase form and the order reads as a person expects. The abs line sorts numbers by their size without their sign, which places -3 last even though it is the smallest value as written. The items stored are still the first items. A key changes only the order they stand in.
A tuple key sorts by two fields at once
A key can return a tuple, and tuples compare field by field. That gives a two-field sort in one pass. Negating a number field turns that one field around without touching the others:
scores = [("ana", 3), ("bo", 5), ("cy", 3)]
print(sorted(scores))
print(sorted(scores, key=lambda row: row[1]))
print(sorted(scores, key=lambda row: (-row[1], row[0])))
rows = [{"name": "ana", "age": 31}, {"name": "bo", "age": 25}, {"name": "cy", "age": 31}]
print([r["name"] for r in sorted(rows, key=lambda r: r["age"])])
The exact output:
[('ana', 3), ('bo', 5), ('cy', 3)]
[('ana', 3), ('cy', 3), ('bo', 5)]
[('bo', 5), ('ana', 3), ('cy', 3)]
['bo', 'ana', 'cy']
The first line needs no key at all. Tuples already compare first field first, so the rows stand by name. The second line sorts by the score field alone, and the two rows with a score of 3 keep their input order, ana before cy. The third line is the full form: the key returns the negated score and then the name, so the highest score stands first and rows tied on score stand by name. Negation works for numbers only. To turn a text field around inside a tuple key, use the two-pass method in the stability section below instead. The last line shows the same key idea on dict rows. A lambda reads the age field out of each dict, and the names print in age order, youngest first.
reverse flips the finished order
The reverse setting flips the order after the key has done its work. It is not the same as sorting forward and reading the list backward, because of the stability rule in the next section:
nums = [3, 1, 4, 1, 5]
print(sorted(nums, reverse=True))
nums.sort(reverse=True)
print(nums)
words = ["banana", "fig", "apple"]
print(sorted(words, key=len, reverse=True))
print(sorted([3, 1, 2])[::-1])
The exact output:
[5, 4, 3, 1, 1]
[5, 4, 3, 1, 1]
['banana', 'apple', 'fig']
[3, 2, 1]
Both tools accept reverse, and both give the same descending order here. The words line shows the setting working with a key: the words compare by length, then the finished order flips, so the longest word stands first. The last line sorts forward and then slices the list backward, which prints the same numbers in this case. The two forms part company when items compare equal. A reverse sort keeps equal items in their input order, while a backward slice turns equal items around. For a plain list of numbers no reader can tell the difference. For rows tied on a key, the difference shows, and reverse is the form that keeps ties in their first order.
Stability: equal items keep their input order
A stable sort never swaps two items that compare equal. That sounds like a footnote until a program sorts twice. The second sort groups items by its key, and inside each group the first order survives:
rows = [("cy", "b", 1), ("ana", "b", 2), ("di", "a", 1), ("bo", "a", 2)]
by_name = sorted(rows, key=lambda r: r[0])
print(by_name)
by_group = sorted(by_name, key=lambda r: r[1])
print(by_group)
pairs = [("x", 2), ("y", 1), ("z", 2), ("w", 1)]
print(sorted(pairs, key=lambda r: r[1]))
The exact output:
[('ana', 'b', 2), ('bo', 'a', 2), ('cy', 'b', 1), ('di', 'a', 1)]
[('bo', 'a', 2), ('di', 'a', 1), ('ana', 'b', 2), ('cy', 'b', 1)]
[('y', 1), ('w', 1), ('x', 2), ('z', 2)]
The first sort stands the rows by name. The second sort stands them by group, and inside group a the names still stand in name order, bo before di, as do ana and cy inside group b. The last sort shows the same rule in one pass: the two rows with a key of 1 keep their input order, y before w, and so do the two with a key of 2. This is the way to sort by a text field descending inside a larger order. Sort by the inner fields first, then sort again by the outer field with reverse set. Each pass keeps what the earlier passes built. A tuple key is shorter when it can express the whole order, and the two-pass form covers the cases a tuple key cannot, such as a descending text field.
sorted takes any iterable and always returns a list
The method belongs to lists alone, but the function takes anything that can be walked: a tuple, a set, a dict, or a string. Whatever goes in, a list comes out:
print(sorted((3, 1, 2)))
print(type(sorted((3, 1, 2))))
print(sorted({3, 1, 2}))
data = {"b": 2, "a": 1, "c": 3}
print(sorted(data))
print(sorted(data.items()))
print(min(data), max(data))
print(sorted("sorting"))
The exact output:
[1, 2, 3]
<class 'list'>
[1, 2, 3]
['a', 'b', 'c']
[('a', 1), ('b', 2), ('c', 3)]
a c
['g', 'i', 'n', 'o', 'r', 's', 't']
A set has no order of its own, so sorting one is a common way to print its values in a form a reader can check. Sorting a dict sorts its keys, because walking a dict yields keys. Sorting its items pairs each key with its value, and the pairs then compare by key first. The min and max functions use the same comparison rule as a sort, so they agree with the ends of a sorted list without building one. When a program needs only the smallest or largest item, those two calls skip the full sort.
Items that cannot be compared raise TypeError
A sort needs one comparison rule that works for every pair. A list that mixes numbers and text has none, and the sort fails instead of guessing:
try:
print(sorted([1, "a", 2]))
except TypeError as e:
print(type(e).__name__)
print(e)
try:
print(sorted([1, None, 2]))
except TypeError as e:
print(type(e).__name__)
print(sorted(["a", "B"], key=str.lower))
nums = [3, 1, 2]
print(sorted(nums, key=lambda n: 0))
The exact output:
TypeError
'<' not supported between instances of 'str' and 'int'
TypeError
['a', 'B']
[3, 1, 2]
None fails the same way, because None has no order against a number. The usual fix is to sort by a key that returns one comparable type for every item, as the str.lower line does for text of mixed case. A key that reads a field out of a dict or a tuple does the same job for rows, as long as that field holds one type across all rows. The last lines show the edge of the rule. A key that returns the same value for every item makes all items equal, a stable sort then keeps the input order, and the list comes back as it went in. When a sort prints its input unchanged, a constant key, or a key that reads the wrong field, is the first place to look.
Which form for which job
| Job | Form | Why |
|---|---|---|
| Sort without changing the source | sorted on the source | The input keeps its first order |
| Sort a list you own, with no copy needed | The sort method on the list | The list rearranges in place |
| Order by length, case, or size without sign | A key function such as len, str.lower, or abs | Items compare by the stand-in value |
| Order by two fields at once | A key that returns a tuple | Tuples compare field by field |
| Highest or longest first | reverse set to True | Ties keep their input order |
| A text field descending inside another order | Two sorts, inner field first | Stability keeps the first order inside groups |
| Sort a tuple, a set, or a dict | sorted on the iterable | The result is always a list |
| Only the smallest or largest item | min or max | No full sort is built |
Checklist
- Before storing the result of a sort call, check which tool you called, because the method returns None.
- Before sorting words for a reader, add a case key, because capitals compare before lowercase letters without one.
- Before negating a field in a tuple key, check that the field is a number, because text cannot be negated.
- Before reading a descending result, check whether ties kept their input order, because a backward slice turns ties around and reverse does not.
- Before sorting rows in two passes, sort by the inner field first, because the later sort is the one that groups.
- Before sorting a mixed list, give every item a key of one type, because mixed numbers and text raise TypeError.
Related guides on this site
- Python Lists, Dicts, and Sets — the containers this guide sorts, and what walking each one yields.
- Python List Comprehensions — Map, Filter, and Nest — the one-line form that often builds the list a sort then orders.
- Python Functions — def, Default Arguments, and Functions as Values — the lambda and function-as-value ideas a key function uses.
- Python Collections — Counter, defaultdict, deque, and namedtuple — the container types whose values often need a sorted print to read.
Sources
- Python, Sorting Techniques — the sorting guide for the key function, the operator module helpers, stability, and the two-field patterns this guide follows.
- Python Tutorial, Data Structures — the tutorial section on the sort method, sorted, and sorting lists of tuples.
Keep Exploring
The full Python hub \u2014 language basics, the standard library, and data tools.
Every guide on the site in one list, grouped by topic.
Every browser-only checker and verifier on the site.
The C++, Python, Sysadmin, Rust, Go, and TypeScript hubs.