Preserve Equal-Key Order with Stable Sorting
Core idea
A stable sort keeps the original relative order of records whose keys compare equal. Use key to choose a field; sorted returns a new list, while list.sort changes the list in place. To sort by several priorities, sort the least significant key first, then the most significant key, or use a tuple key when all directions agree.
rows = [('A', 2), ('B', 1), ('C', 2)]print([name for name, _ in sorted(rows, key=lambda r: r[1])])B moves first; A stays before C because their keys tie.
Two priorities
rows = [('B', 2), ('A', 2), ('C', 1)]rows.sort(key=lambda r: r[0])rows.sort(key=lambda r: r[1], reverse=True)print(rows)Descending priority is primary; ascending name breaks ties.
Common mistake
Reversing an already sorted list also reverses ties; reverse=True on a stable sort preserves tie order.
Practice
Sort three shipment records by descending weight, retaining arrival order for equal weights. Compare with reversing an ascending sort.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Stable sorting and keys
Check your understanding of stable sorting and keys.
What is printed?
print(sorted(['bb','a','cc'], key=len))What is printed?
print(sorted(['ab','cd','x'], key=len, reverse=True))Which key is sorted first in two stable passes?
What does list.sort return?