sorted() with
Key Functions
Master Python's sorted() built-in to sort any iterable using custom key functions and the reverse parameter.
What is sorted()?
Python's sorted() is a built-in function that takes any iterable (list, tuple, string, etc.) and returns a new sorted list. Unlike the .sort() method, it never modifies the original data.
The Full Signature
Why Key Functions Matter
By default, sorted() compares elements using their natural ordering (numbers by value, strings alphabetically). But what if you need to sort by string length, absolute value, or a specific attribute?
How key Works Internally
When you pass key=some_function, Python calls that function on every element, then sorts by the returned values. The final list contains the original elements, not the transformed ones.
sorted() vs .sort()
| sorted(iterable) | list.sort() | |
|---|---|---|
| Returns | New list | None |
| Mutates original? | No | Yes |
| Works on | Any iterable | Lists only |
| key parameter | ✓ | ✓ |
| reverse parameter | ✓ | ✓ |
| Use case | Need original intact | Sort list in place |
How to Apply Key Functions
Example 1: Sort by Absolute Value
Sort a list of positive and negative numbers by their distance from zero, ignoring the sign.
Example 2: Lambda Key Functions
Sort a list of tuples by their second element using a lambda function.
Example 3: Descending with reverse
Combine key and reverse to sort students by grade from highest to lowest.
Example 4: Sorting Dictionaries
Sort a list of dictionaries by a specific key, such as "price".
Example 5: Case-Insensitive Sorting
By default, Python sorts uppercase letters before lowercase. Use key=str.lower to ignore case.
Stable Sorting and Multi-Key
Python's sort is stable: elements that compare equal keep their original relative order. This lets you chain sorts for multi-key sorting, or use a tuple key.
Common Key Functions Reference
| Key | Sorts by | Example Use |
|---|---|---|
| len | String/list length | Shortest to longest |
| abs | Absolute value | Distance from zero |
| str.lower | Lowercase version | Case-insensitive sort |
| lambda x: x[1] | Second element | Tuples, nested lists |
| lambda x: x["key"] | Dictionary value | List of dicts |
| lambda x: (a, b) | Multiple criteria | Multi-key sort |
Common Mistakes
Question 1 of 5
What does sorted() return?
Question 2 of 5
Given words = ["fig", "banana", "kiwi", "apple"], what does sorted(words, key=len) return?
Question 3 of 5
What is wrong with this code?
sorted(my_list, abs)
Question 4 of 5
Given pairs = [(1, "z"), (3, "a"), (2, "m")], what does sorted(pairs, key=lambda p: p[1]) return?
Question 5 of 5
What does the reverse=True parameter do in sorted()?