Master Python’s Stable Sorting: Using sorted() with key and reverse
Python’s sorted() function offers stable sorting, allowing multi‑criteria ordering through successive sorts, while its flexible key parameter lets you customize sorting logic—such as sorting by length then alphabetically—and the reverse flag enables effortless descending order, making complex sorting tasks straightforward.
Sorting in Python seems simple until you notice some quirks.
sorted() is stable
The sorted() function is stable, meaning that when two elements compare equal they retain their original order, which is useful for multi‑criteria sorting.
For example, to sort a list of people first by age then by name you can perform two sorts leveraging stability:
<code>people = [
{"name": "Alice", "age": 25},
{"name": "Bob", "age": 30},
{"name": "Charlie", "age": 25}
]
# First sort by name
people.sort(key=lambda x: x["name"])
# Then sort by age
people.sort(key=lambda x: x["age"])
print(people)
</code>In the final list, Alice and Charlie both have age 25, but because the name sort was applied first, Alice remains before Charlie.
Using key parameter for custom sorting — more flexible than you think
The key parameter of sorted() can accept any function that returns a value, allowing you to combine and transform values for advanced sorting.
For instance, to sort strings by length and then alphabetically you can create a tuple in the key function:
<code>words = ["banana", "apple", "pear", "blueberry", "kiwi"]
sorted_words = sorted(words, key=lambda x: (len(x), x))
print(sorted_words)
</code>Here the key function first sorts by len(x) and then by the string itself, which is handy when you need multi‑criteria sorting without multiple calls to sorted() .
Additional tip: Easy reverse sorting
The sorted() function has a reverse parameter; setting it to True yields descending order without modifying the key function.
<code>numbers = [4, 2, 9, 1]
sorted_numbers = sorted(numbers, reverse=True)
print(sorted_numbers)
</code>The sorted() function in Python is powerful: from its stability to the flexibility of the key parameter and the convenience of reverse , it enables you to handle complex sorting tasks easily and avoid unexpected behavior.
Code Mala Tang
Read source code together, write articles together, and enjoy spicy hot pot together.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.