key is a function of one item
sorted(words, key=len)
key is called once per item and returns the value to sort on. Here len turns each word into its length. The words come back shortest first. The items in the result are still the original words. Only the comparison changed.
Any callable works: a builtin function, a lambda, or a named function you wrote yourself.
sorted(people, key=lambda p: p[1]) # by the second element
sorted(rows, key=lambda r: r["score"]) # by a dict field
Without a key argument, sorted compares items directly. That works fine for numbers and strings. Numbers sort by value. Strings sort by character code, which means uppercase letters come before lowercase and digits come before letters. For a list of plain integers, you never need key.
The need appears the moment your items are not simple values. A list of tuples representing people, a list of dictionaries from an API response, a list of file paths you want ordered by size: in every case, the thing you want to sort by is not the item itself but some property of it. The key function extracts that property.
A common beginner mistake is writing the key function so it modifies the item or returns the wrong type. The key function should be a pure function that takes one item and returns a comparable value. It should not print, it should not mutate, and it should not have side effects. Think of it as answering the question: "by what value should this item be ranked?"
The reverse=True parameter flips the order. sorted(scores, reverse=True) gives highest first. You can combine it with key: sorted(people, key=lambda p: p[1], reverse=True) sorts people by the second element, highest first.
The built-in sorted always returns a new list. The list method .sort() sorts in place and returns None. The key parameter works the same way on both.
This page covers how key works, sorting with lambdas and named functions, reverse, the difference between sorted() and .sort(), and sorting by multiple criteria with tuples.
sorted() versus .sort()
new = sorted(nums) # a new list, original untouched
nums.sort() # rearranges in place, returns None
The trap is writing nums = nums.sort(). This Assigns None and destroys the list. It's a common enough mistake that recognising it's worth more than the rule. If a sort made None, this is why.
.sort() exists only on lists. sorted() accepts any iterable. A tuple, a string, a set, a dict (giving its keys). And always hands back a list.
Stability, and why it matters
Python's sort is stable: items that compare equal keep their first scaled order. That is what makes multi-pass sorting work. Sort by name, then sort the result by score. Entries with the same score are still in name order. The page shows this right, sorting only by the number and pointing out that the tied items didn't shuffle.
key is called just once per item, not on each check. An costly key function is affordable. Doing the same work inside a check would cost far more.
Sorting by more than one thing
Return a tuple, and the sort checks spot by spot:
sorted(people, key=lambda p: (p.surname, p.forename))
Surname first, forename only where surnames match. This extends to as many levels as you need, and it's far easier to get right than sorting again and again.
Mixing directions is the awkward case, because reverse=True applies to the whole sort. For numbers, negating one component works: key=lambda p: (-p.score, p.name) gives highest score first, then name ascending. For strings there's no negation, and the usual answer is two stable sorts, applied least major first.
Why in-place methods return None
nums.sort() returning None looks like an oversight and is a deliberate rule that runs through the whole standard library. list.reverse, list.append, list.extend, dict.update and set.add all return None for the same reason: they changed the object rather than making a new one, and returning the object would invite x = x.sort(). This Reads as though a new list came back.
By returning nothing, the method makes that line obviously wrong the moment you try to use the result. The None isn't a missing return value. It's the signal that the work happened a place else.
Once the rule is familiar it turns a reading aid. A method that returns None mutated a thing. A function that returns a value left its inputs alone. sorted, reversed, sorted's relatives in itertools, and each string method follow the second pattern. This Is why none of them ever surprise you by changing what you passed in.
The same key everywhere
key isn't a sorting feature. min, max and itertools.groupby all take it and mean the same thing by it. So max(people, key=lambda p: p.score) finds the top scorer without sorting any of it - which is both faster and clearer than sorting and taking the last element.
A worked example: ranking records
The shape that comes up constantly. Sort records by one field, break ties with another, and print them aligned:
rows = [
{"name": "ana", "score": 91, "team": "red"},
{"name": "bo", "score": 78, "team": "blue"},
{"name": "cy", "score": 91, "team": "blue"},
]
for r in sorted(rows, key=lambda r: (-r["score"], r["name"])):
print(f"{r['name']:<5}{r['score']:>4} {r['team']}")
ana 91 red
cy 91 blue
bo 78 blue
The key returns a tuple. So The sort checks scores first and names only where scores tie. The minus sign reverses the score alone, which reverse=True could not do — it would have reversed the names as well, putting cy before ana.
This is worth having in your fingers, because "highest first, then alphabetical" is what almost each leaderboard, report and ranking really wants, and it's one formula rather than a check function.
Sorting things that cannot be compared
Python refuses to guess an order between unrelated types:
try:
sorted([3, "1", 2])
except TypeError as e:
print("TypeError:", e)
TypeError: '<' not supported between instances of 'str' and 'int'
This is deliberate. Languages that allow it give orderings that depend on setup details, and the resulting bugs are far worse than an exception. The fix is to say what you mean with a key: key=str to sort them as text, key=int if they're all numeric in disguise.
None is the version of this that shows up in real data, because a missing field is very often None and None can't be checked with any of it. Rather than filtering the rows out, put the missing ones at one end:
rows = [("ana", 91), ("bo", None), ("cy", 78)]
print(sorted(rows, key=lambda r: (r[1] is None, r[1])))
[('cy', 78), ('ana', 91), ('bo', None)]
The first element of the key is a boolean, and False sorts before True, so all with a value comes first and the missing ones collect at the end. Swap it to r[1] isn't None to put them first instead. The second element is only ever checked between rows that agree on the first, so None is never checked with a number.
Case, accents and numbers inside strings
Sorting text has three traps that only appear once the data stops being tidy.
Case. The default sort is by code point. So Each capital letter sorts before each lowercase one and ["banana", "Apple"] comes back with Apple first. key=str.lower fixes it, and key=str.casefold is the stricter version for text that isn't ensured to be English.
Accents. é sorts after z by code point. This Is wrong in each language that uses it. The standard library's locale.strxfrm sorts per to the user's locale, and for any of it serious the PyICU library does it properly. For an inner report, unicodedata.norm plus stripping the mixing marks is often enough.
Numbers inside names. ["file10", "file2"] sorts with file10 first, because 1 is before 2 as text. This is the "natural sort" problem, and the fix is a key that splits the string into text and numeric runs and converts the numeric ones, so the check happens between ints rather than digits.
All three have the same shape as all else on this page: the data isn't what you want to compare. So Transform it in the key and leave it alone in the result.
What sorting costs, and when not to
Python's sort is Timsort. This Is O(n log n) and a lot faster than that on data with existing order — already-sorted input is close to linear, and so is data made of sorted runs. That isn't an accident; it was designed for real data. This Is often partly sorted.
The hands-on consequence is that sorting is cheap enough to stop thinking about at plain sizes. Where it's worth thinking about is when you don't really need a sorted sequence:
If you want the single largest or smallest item, max and min take the same key and do it in one pass rather than n log n. If you want the top few, heapq.nlargest(k, items, key=...) beats sorting when k is small scaled to n. If you want to know whether any of it qualifies, any with a gen stops at the first hit. And if you're sorting the same list again and again inside a loop, sort it once outside the loop instead.
The one that catches people is sorting to find a max. sorted(items)[-1] is correct, does far more work than needed, and reads less clearly than max(items).
Grouping, which needs sorting first
itertools.groupby merges runs of equal items into groups, and it's the most common reason to sort a thing you didn't or else need in order.
The key property is that it only groups *adjacent* items. It walks the sequence once and starts a new group when the key changes, which means unsorted input makes a group each time the value changes back and forth rather than one group per distinct value. Sorting by the same key first is what makes the grouping complete, and losing to is the single mistake everyone makes with it once.
from itertools import groupby
rows = [("red", "ana"), ("blue", "bo"), ("red", "cy")]
rows.sort(key=lambda r: r[0])
for team, members in groupby(rows, key=lambda r: r[0]):
print(team, [m for _, m in members])
blue ['bo']
red ['ana', 'cy']
The same key appears twice, in the sort and in the group, and it has to be the same key for the result to make sense. The second thing to know is that the groups are iterators over the first sequence, not lists, and they become invalid once you move to the next group. Which is why the example materialises each one inside the loop rather than collecting the groups and using them afterwards.
For grouping without sorting, a defaultdict(list) and a single loop is simpler, doesn't need order, and gives you real lists. groupby earns its place when the data is already sorted, when the sequence is too large to hold, or when you want the runs rather than the totals.
Making your own objects sortable
key= handles most cases, and at times the sorting belongs to the object itself rather than to one call site. Then the object should carry it.
Defining __lt__ is enough for sorted, min and max, because they need only "is this one less than that one". The other checks — <=, >, >= — are separate methods and aren't inferred. So An object with only __lt__ sorts right and raises on >=. functools.total_ordering fills the rest in from __lt__ and __eq__, at a small runtime cost.
The shorter route is a dataclass. @dataclass(order=True) writes all six check methods, checking the fields in the order they're declared, which is just the tuple-key action with the tuple written for you. Fields you don't want in the check are excluded with field(compare=False), which is how you keep a name or an id out of the sorting while leaving it on the object.
The judgement is about where the sorting belongs. If there's one natural order for the type — a version number, a date range, a playing card — put it on the class and each call site gains. If different callers want different orders, key= at each call site is the honest answer, and building one in as "the" order will mislead the next reader.
One rule applies whichever you choose: the sorting must be steady with equality, and it must be total. Objects that compare equal must not also compare less-than, and each pair must be close. A sort that receives an inconsistent sorting doesn't raise. It makes a result that is quietly wrong and changes with the input order.
Questions people ask about sorted() with key=
Can key return any of it? any of it close with itself. Numbers, strings and tuples of those are the usual choices.
How do I sort descending by one field and ascending by another? Negate the descending one in a tuple key, or do two stable sorts, least major first.
Does sorted work on a dict? Yes, and it sorts the keys. Use d.items() when you want pairs.
Is reverse=True the same as reversing afterwards? Not just. reverse=True keeps ties in their first order. Sorting then reversing flips the ties too.
What happened to cmp? Removed in Python 3. If you truly need a check function, functools.cmp_to_key converts one into a key.
Can I sort a gen? Yes — sorted accepts any iterable and returns a list. It has to consume the whole thing to do it.
Why is my sort not stable? It's. If tied items appear to move, the key is distinguishing them in a way you didn't intend.
Does sorting a list of dicts need a key? Yes. Dicts aren't orderable, so without one you get a TypeError.
How large can a list be before sorting is slow? Far larger than most programs handle. Sorting a million small items takes well under a second, and the cost is often dominated by what built the list.
sorted() with key=: recap in one screen
key transforms each item once and sorts on the result. The items you get back are unchanged.- A tuple key gives tiebreaks. Negate a number to reverse one field without reversing the rest.
sorted returns a new list, .sort() returns None — that None is the rule for each in-place method.- The sort is stable. This Is what makes two-pass sorting work.
max, min, heapq.nlargest and groupby take the same key. Reach for them when you don't need all in order.
When you do not need the whole thing in order
sorted(..., key=...) puts each element in order. This Is more than most questions ask for. If you only want the largest few, a sort does work you then discard — heapq does the smaller job, holding k items instead of n.
The gap is measurable rather than asymptotic hand-waving. On a list with many distinct keys, a full sort took 155.9 ms where nlargest took 11.9 ms. On a list with only a handful of distinct values, the sort *won*. Which way it falls is a property of the data, not of the form.