In Python, the key argument of sorted() and list.sort() is a function that is called once for each element and returns the value used for comparison. The elements themselves are not changed; only the order is decided by the keys. For example, sorted(words, key=len) sorts strings by their length.
Understanding the Python sort key function lets you sort objects, tuples, dictionaries and mixed data without writing your own comparison code. This guide uses Python 3.13.
When you call sorted(items, key=f), Python computes f(item) once for every item, stores those results, and then sorts the items by comparing the stored results. The original items are returned in the new order.
The first line sorts alphabetically, the default. The second sorts by length. Notice that banana stays before cherry because both have six letters and Python's sort is stable, so equal keys keep their original order.
The key function takes exactly one argument. Anything you can call with one argument works: built-in functions such as len and str.lower, a lambda, a regular function, or a method.
Passing an existing function is the simplest form and needs no parentheses, because you hand over the function, not its result.
Plain sorting puts uppercase letters before lowercase because it compares Unicode code points. str.lower gives a case-insensitive order, and str.casefold is the more aggressive, correct choice for international text.
A frequent mistake is writing key=len() or key=str.lower(). That calls the function immediately and raises a TypeError. Drop the parentheses.
When the value you need is not a ready-made function, write a small one. A lambda is fine for one-liners; use a named function when the logic needs a name or several lines.
For the common cases of "get an item" or "get an attribute", the operator module has itemgetter and attrgetter. They are implemented in C and are a little faster than the equivalent lambda.
Add reverse=True for descending order. The sorted() function returns a new list and accepts any iterable. The list.sort() method sorts the list in place and returns None.
A common bug is nums = nums.sort(), which sets nums to None. Use sorted() when you want a value back, and .sort() when you want to modify the list.
The key function runs once per element, not once per comparison. That is the main reason keys replaced the old cmp argument, which was removed in Python 3. It means the cost is n key calls plus an O(n log n) sort of the cached keys.
Because of this, the key should be cheap and should not have side effects. If computing a key is expensive, for example a file lookup, compute it once yourself or cache it.
If you really have an old-style comparison function that takes two arguments, convert it with functools.cmp_to_key. Prefer a key function when you can, because it is simpler and faster.
It names a one-argument function that turns each element into the value Python compares. The original elements are returned, just in the order of their keys.
Either you called the function instead of passing it (key=len()), or the keys cannot be compared with each other, such as a number and None. Make every key the same comparable type.
Both give the same result. itemgetter and attrgetter are slightly faster and read well for simple lookups; a lambda is better for any custom expression.
Yes. Return a tuple and Python compares it element by element, which is how you sort by multiple keys.
The key function of sorted() and list.sort() converts each element into the value used for ordering, and it is called once per element. Pass the function without parentheses, use str.lower, len, a lambda, itemgetter or attrgetter as needed, add reverse=True for descending order, and remember that list.sort() returns None. Use functools.cmp_to_key only when you must reuse an old comparison function.