01 / 20

sorted() with
Key Functions

Master Python's sorted() built-in to sort any iterable using custom key functions and the reverse parameter.

Python

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.

nums = [5, 2, 8, 1, 9] sorted(nums) # Returns: [1, 2, 5, 8, 9] # nums is still [5, 2, 8, 1, 9]

The Full Signature

sorted(iterable, *, key=None, reverse=False)
iterable
Any iterable: list, tuple, string, set, dict, generator, etc.
key
A function applied to each element before comparing. Default: None (compare elements directly).
reverse
Boolean. If True, sort in descending order. Default: False (ascending).

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?

Default sort ["banana", "fig", "apple", "kiwi"] ["apple", "banana", "fig", "kiwi"] Alphabetical (A-Z) key=len sort ["banana", "fig", "apple", "kiwi"] ["fig", "kiwi", "apple", "banana"] By length (3, 4, 5, 6) The key function transforms WHAT gets compared, not WHAT gets returned.

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.

Original "banana" "fig" "apple" "kiwi" key=len 6 3 5 4 Sorted Result "fig" "kiwi" "apple" "banana" len=3 len=4 len=5 len=6 Original elements are rearranged, NOT the key values!

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

1
Identify the sorting criterion. What property should determine order? (length, absolute value, dictionary key, attribute, etc.)
2
Write a function that extracts it. The function takes one element and returns the comparable value. Use a named function, lambda, or built-in.
3
Pass it as key=your_function. Do not call the function with parentheses: pass the function object itself.
4
Add reverse=True if needed. For descending order, set the reverse parameter.
5
Capture the result. sorted() returns a new list: assign it to a variable.

Example 1: Sort by Absolute Value

Sort a list of positive and negative numbers by their distance from zero, ignoring the sign.

nums = [-7, 3, -1, 5, -4, 2] result = sorted(nums, key=abs) print(result)
→ [-1, 2, 3, -4, 5, -7]

Example 2: Lambda Key Functions

Sort a list of tuples by their second element using a lambda function.

students = [ ("Alice", 88), ("Bob", 72), ("Carol", 95), ("Dave", 81) ] by_grade = sorted(students, key=lambda s: s[1]) print(by_grade)
→ [("Bob", 72), ("Dave", 81), ("Alice", 88), ("Carol", 95)]

Example 3: Descending with reverse

Combine key and reverse to sort students by grade from highest to lowest.

students = [ ("Alice", 88), ("Bob", 72), ("Carol", 95), ("Dave", 81) ] top_first = sorted(students, key=lambda s: s[1], reverse=True) print(top_first)
→ [("Carol", 95), ("Alice", 88), ("Dave", 81), ("Bob", 72)]

Example 4: Sorting Dictionaries

Sort a list of dictionaries by a specific key, such as "price".

items = [ {"name": "Book", "price": 12.99}, {"name": "Pen", "price": 1.50}, {"name": "Laptop", "price": 899.00}, {"name": "Notebook", "price": 4.75} ] by_price = sorted(items, key=lambda x: x["price"]) for item in by_price: print(item["name"], item["price"])
→ Pen 1.5 → Notebook 4.75 → Book 12.99 → Laptop 899.0

Example 5: Case-Insensitive Sorting

By default, Python sorts uppercase letters before lowercase. Use key=str.lower to ignore case.

words = ["banana", "Apple", "cherry", "Date"] # Default: uppercase comes first sorted(words) # → ['Apple', 'Date', 'banana', 'cherry'] # Case-insensitive sorted(words, key=str.lower) # → ['Apple', 'banana', 'cherry', 'Date']

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.

data = [ ("Alice", "Math", 92), ("Bob", "Math", 85), ("Alice", "English", 88), ("Bob", "English", 91) ] # Sort by name, then by grade descending result = sorted(data, key=lambda x: (x[0], -x[2])) # → [("Alice","Math",92), ("Alice","English",88), # ("Bob","English",91), ("Bob","Math",85)]

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

✕ Calling the function
Writing key=len() instead of key=len. The parentheses call len with no arguments, causing a TypeError.
✕ Forgetting key=
Writing sorted(data, len) instead of sorted(data, key=len). Key and reverse are keyword-only arguments.
✕ Not capturing return
Writing sorted(mylist) without assigning it. sorted() returns a new list: the result is lost if not stored.

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()?