01 / 20

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.

Python

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.

Unsorted 38 12 5 sort Sorted 5 12 38 Python makes this easy with built-in tools.

Two Built-in Sorting Tools

sorted()
A built-in function that accepts any iterable and returns a new sorted list. The original stays unchanged.
list.sort()
A list method that sorts the list in place and returns None. Only works on lists.
nums = [38, 12, 5] # sorted() returns a new list result = sorted(nums) # [5, 12, 38] print(nums) # [38, 12, 5] (unchanged) # list.sort() modifies in place nums.sort() print(nums) # [5, 12, 38] (changed!)

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

sorted(iterable, key=function, reverse=False) list.sort(key=function, reverse=False)
key
A callable that takes one argument and returns the value Python uses for comparisons.
reverse
Set to True to sort in descending order (largest first).

How key Works Under the Hood

Original List "fig" "kiwi" "apple" key=len Sort Values 3 4 5 Sorted by Length "fig" "kiwi" "apple" Result reorder originals len 3 len 4 len 5

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

1
Identify your data. What type of iterable do you have: list of numbers, strings, tuples, dicts?
2
Decide the sort property. What should Python compare: length, a field, absolute value, lowercase form?
3
Write a key function. Use a built-in like len or str.lower, or write a lambda.
4
Choose sorted() or .sort(). Need a new list? Use sorted(). Modify in place? Use .sort().
5
Set reverse if needed. Pass reverse=True for descending order.

Example 1: Sort by String Length

words = ["banana", "kiwi", "fig", "cherry"] by_length = sorted(words, key=len) print(by_length) # ['fig', 'kiwi', 'banana', 'cherry']

Example 2: Case-Insensitive Sort

names = ["Zara", "alice", "Bob"] # Default: uppercase comes before lowercase print(sorted(names)) # ['Bob', 'Zara', 'alice'] # Case-insensitive with key=str.lower print(sorted(names, key=str.lower)) # ['alice', 'Bob', 'Zara']

Example 3: Lambda Key Functions

When no built-in function does what you need, write a lambda: a small anonymous function defined inline.

students = [ ("Alice", 92), ("Bob", 85), ("Carol", 97), ] # Sort by grade (second element of tuple) by_grade = sorted(students, key=lambda s: s[1]) # [('Bob', 85), ('Alice', 92), ('Carol', 97)] # Highest grade first top_first = sorted(students, key=lambda s: s[1], reverse=True) # [('Carol', 97), ('Alice', 92), ('Bob', 85)]

Example 4: Sorting Dictionaries

products = [ {"name": "Laptop", "price": 999}, {"name": "Mouse", "price": 25}, {"name": "Keyboard", "price": 75}, ] # Sort by price, cheapest first by_price = sorted(products, key=lambda p: p["price"]) # Result: # [{'name': 'Mouse', 'price': 25}, # {'name': 'Keyboard', 'price': 75}, # {'name': 'Laptop', 'price': 999}]

The reverse Parameter

nums = [3, 1, 4, 1, 5, 9] # Ascending (default) print(sorted(nums)) # [1, 1, 3, 4, 5, 9] # Descending print(sorted(nums, reverse=True)) # [9, 5, 4, 3, 1, 1] # Combine with key: longest strings first words = ["hi", "hello", "hey"] print(sorted(words, key=len, reverse=True)) # ['hello', 'hey', 'hi']

Stable Sorting Guarantee

Python's sort is stable: when two elements have equal key values, they keep their original relative order.

data = [("B", 2), ("A", 1), ("C", 2)] # Sort by number result = sorted(data, key=lambda x: x[1]) # [('A', 1), ('B', 2), ('C', 2)] # ^ ^ # B came before C originally, so it stays first

Common Mistakes

✕ Calling the key function
Writing key=len() instead of key=len. You must pass the function itself, not its result.
✕ Assigning .sort() result
Writing x = my_list.sort() gives x = None because .sort() returns None.
✕ Sorting mixed types
Comparing int and str raises a TypeError. Ensure all key values share a comparable type.

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?