Unlike list.sort(), which sorts a list in place and returns None, sorted() works on any iterable, not just lists, always returns a brand-new list, and never modifies its input. Its key parameter takes a function used to compute a comparison value for each element, for example sorting case-insensitively or by length, and reverse=True flips the order to descending. Python's sort algorithm, Timsort, is stable, meaning equal elements keep their original relative order.
1Understanding sorted()
Unlike list.sort(), which sorts a list in place and returns None, sorted() works on any iterable, not just lists, always returns a brand-new list, and never modifies its input. Its key parameter takes a function used to compute a comparison value for each element, for example sorting case-insensitively or by length, and reverse=True flips the order to descending. Python's sort algorithm, Timsort, is stable, meaning equal elements keep their original relative order.
sorted() and list.sort() both accept key= and reverse= — use sorted() when you need to keep the original order too, and .sort() only when you specifically want to mutate in place and don't need the old order.
numbers = [5, 2, 8, 1, 9]
print(sorted(numbers))
print(sorted(numbers, reverse=True))2Practical Example
Here is a real-world application of sorted() showing how it is used in production Python code.
students = [{"name": "Boris", "grade": 82}, {"name": "Ana", "grade": 91}]
ranked = sorted(students, key=lambda s: s["grade"], reverse=True)
print([s["name"] for s in ranked])3Best Practices
Follow these guidelines when working with sorted():
1. Use key= instead of a custom comparator function — it's simpler, and Python has removed the older comparator-function style entirely
2. Sort a dictionary's items by value using key= on the items() view instead of manual loops
3. Rely on Timsort's stability when you need a secondary sort key to preserve a previous sort's order for ties
Tip: sorted() and list.sort() both accept key= and reverse= — use sorted() when you need to keep the original order too, and .sort() only when you specifically want to mutate in place and don't need the old order.
numbers = [5, 2, 8, 1, 9]
print(sorted(numbers))
print(sorted(numbers, reverse=True))