Python sorted() & key Functions
In this page:
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()
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
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
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
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
people = [{"name": "Alex", "age": 30}, {"name": "Sam", "age": 25}]
print(sorted(people, key=lambda p: p["age"]))
Chapter Quiz — Complete all 15 topics to unlock
0/15 topics done
Complete these topics first:
- Python PEP 8 Style Guide
- Python Debugging Techniques
- Python Testing with unittest
- Python Common Mistakes
- Python Interview Questions
- Python map() & filter()
- Python reduce()
- Python zip() & enumerate()
- Python sorted() & key Functions
- Python Comprehensions Advanced
- Python Turtle Graphics
- Python tkinter Introduction
- Python tkinter Widgets
- Python pygame Introduction
- Python Mini Projects