← Back to Python Course | Chapter 14: Advanced Python & Tools | Lesson 9 of 15

Python sorted() & key Functions

Standard Sorting with sorted()

sorted(iterable) returns a brand-new sorted list, leaving the original iterable untouched -- distinct from a list's own .sort() method, which sorts in place and returns None. Reaching for the wrong one is a common source of confusing bugs where a variable unexpectedly becomes None.

Example: Standard Sorting with sorted()

python
numbers = [3, 1, 2]
result = sorted(numbers)
print(result, numbers)

Sorting in Reverse Order

sorted() orders elements ascending by default; passing reverse=True flips that to descending order without needing to sort ascending and then separately reverse the result.

Example: Sorting in Reverse Order

python
numbers = [3, 1, 2]
print(sorted(numbers, reverse=True))

Sorting with Custom Key Functions

The key parameter accepts a function that's applied to each element to compute the value actually used for comparison, letting you sort by a derived property (like a string's length) rather than the elements' natural ordering.

Example: Sorting with Custom Key Functions

python
words = ["banana", "kiwi", "apple"]
print(sorted(words, key=len))

Sorting with Lambda Keys

A lambda is the typical way to supply a key function inline, especially for simple derivations like key=lambda x: x[1] to sort tuples by their second element, without the overhead of defining a separate named function elsewhere.

Example: Sorting with Lambda Keys

python
pairs = [(1, "b"), (2, "a")]
print(sorted(pairs, key=lambda x: x[1]))

Sorting Complex Lists

Sorting a list of dictionaries or custom objects by a specific field is the most common real-world use of key -- sorted(people, key=lambda p: p[age]), for instance, sorts a list of person-records by age without needing any custom comparison logic beyond naming which field matters.

Example: Sorting Complex Lists

python
people = [{"name": "Alex", "age": 30}, {"name": "Sam", "age": 25}]
print(sorted(people, key=lambda p: p["age"]))

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.