Sorting with
Key Functions
Master Python's sorted() and list.sort() to arrange data any way you want: by length, by value, by custom logic using key functions.
What Is Sorting?
Sorting means rearranging items in a sequence so they follow a defined order: smallest to largest, alphabetical, shortest to longest, or any rule you choose.
Two Built-in Sorting Tools
Why Key Functions Matter
Default sorting uses Python's natural ordering: numbers go smallest→largest, strings go alphabetical. But what if you need to sort words by length, names by last name, or records by a specific field?
The key parameter lets you pass a function that transforms each element into a "sort value." Python compares these transformed values instead of the originals.
The Syntax
How key Works Under the Hood
sorted() vs list.sort()
| sorted() | list.sort() | |
|---|---|---|
| Type | Built-in function | List method |
| Accepts | Any iterable | Lists only |
| Returns | New list | None (in-place) |
| Original | Unchanged | Modified |
| key param | ✓ Supported | ✓ Supported |
| reverse param | ✓ Supported | ✓ Supported |
Step-by-Step Approach
Example 1: Sort by String Length
Example 2: Case-Insensitive Sort
Example 3: Lambda Key Functions
When no built-in function does what you need, write a lambda: a small anonymous function defined inline.
Example 4: Sorting Dictionaries
The reverse Parameter
Stable Sorting Guarantee
Python's sort is stable: when two elements have equal key values, they keep their original relative order.
Common Mistakes
Summary Reference
| Task | Code |
|---|---|
| Sort numbers ascending | sorted(nums) |
| Sort numbers descending | sorted(nums, reverse=True) |
| Sort strings by length | sorted(words, key=len) |
| Case-insensitive sort | sorted(names, key=str.lower) |
| Sort tuples by field | sorted(data, key=lambda x: x[1]) |
| Sort dicts by key | sorted(lst, key=lambda d: d["k"]) |
| In-place sort | my_list.sort(key=...) |
Question 1 of 5
What does sorted() return when called on a list?
Question 2 of 5
Given words = ["cherry", "fig", "kiwi"], what is the result of sorted(words, key=len)?
Question 3 of 5
What is wrong with this code?
result = my_list.sort()
Question 4 of 5
Given pairs = [("a", 3), ("b", 1), ("c", 2)], which expression sorts them by their second element in descending order?
Question 5 of 5
Why does writing key=len() with parentheses cause an error, while key=len works correctly?