01 / 20

Stable Sorting
in Python

Understand why order preservation matters when sorting, how Python's built-in sort guarantees stability, and when it changes the outcome of your programs.

Python

What Does Sorting Really Mean?

Sorting rearranges a collection of items into a defined order: alphabetical, numerical, by date, by priority, and so on. In Python you use sorted() or list.sort() every day.

But what happens when two items compare as equal? For example, two students with the same grade, or two products at the same price. The answer depends on whether your sorting algorithm is stable.

Defining Stable Sorting

Stable Sort
If two elements compare as equal, they appear in the same relative order in the output as they did in the input.
Unstable Sort
Equal elements may be rearranged relative to each other. Their output order is not guaranteed.

Why Does Stability Matter?

Imagine a spreadsheet of student records already sorted by name. You then sort by grade. With a stable sort, students sharing the same grade remain in alphabetical order. With an unstable sort, the alphabetical order within each grade is destroyed.

INPUT (sorted by name) Alice: A Bob: B Carol: A Dave: B STABLE (sort by grade) Alice: A Carol: A Bob: B Dave: B ✓ Alice before Carol ✓ Bob before Dave UNSTABLE (sort by grade) Carol: A Alice: A Dave: B Bob: B ✕ Order flipped! ✕ Order flipped! Grade A Grade B

The Formal Definition

In plain language: equal elements never swap positions relative to each other. The original ordering is preserved within each group of ties.

This is a property of the algorithm, not the data. Some algorithms are inherently stable (Merge Sort, Insertion Sort, Timsort). Others are inherently unstable (Quicksort, Heapsort) unless modified.

Visualising Stability

Input list: sort by number only 3 RED 1 BLUE 3 GRN 2 AMB 2 PNK Stable output 1 BLUE 2 AMB 2 PNK 3 RED 3 GRN AMB before PNK ✓ RED before GRN ✓ Original input order preserved for equal keys

Python Uses Timsort

Python's sorted() and list.sort() both use Timsort, a hybrid sorting algorithm created by Tim Peters in 2002. Timsort combines Merge Sort and Insertion Sort. Its key properties:

Stable
Equal elements always keep their original relative order.
Adaptive
Runs faster on partially sorted data: best case \( O(n) \).
Guaranteed
Worst-case time: \( O(n \log n) \). Space: \( O(n) \).

Stable vs Unstable Algorithms

Algorithm Stable? Time (avg) Used In
Timsort ✓ Yes \( O(n \log n) \) Python, Java
Merge Sort ✓ Yes \( O(n \log n) \) General use
Insertion Sort ✓ Yes \( O(n^2) \) Small arrays
Quicksort ✕ No \( O(n \log n) \) C stdlib
Heapsort ✕ No \( O(n \log n) \) Embedded

The Power of Multi-Key Sorting

Because Python's sort is stable, you can sort by multiple criteria by sorting multiple times: sort by the least important key first, then by the most important key last.

# Students: (name, grade) students = [("Carol", "A"), ("Alice", "B"), ("Bob", "A"), ("Dave", "B")] # Step 1: sort by name (secondary key) students.sort(key=lambda s: s[0]) # Step 2: sort by grade (primary key) students.sort(key=lambda s: s[1]) # Result: [('Bob', 'A'), ('Carol', 'A'), # ('Alice', 'B'), ('Dave', 'B')]

How to Apply Stable Sorting

1
Identify your keys. Determine which fields you want to sort by: primary, secondary, and so on.
2
Sort least-important first. Call sort() or sorted() with the least-significant key first.
3
Then sort by most-important. Each successive sort preserves the order from the previous pass for equal keys.
4
Or use a tuple key. Alternatively, pass a tuple: key=lambda x: (primary, secondary) for a single-pass approach.

Example 1: Sorting Tuples

data = [(3, "banana"), (1, "cherry"), (3, "apple"), (2, "date")] result = sorted(data, key=lambda x: x[0])

We sort only by the number (index 0). The two items with key 3 are (3, "banana") and (3, "apple").

Example 2: Two-Pass Sort

tasks = [ {"name": "Deploy", "pri": 2, "due": "Mon"}, {"name": "Test", "pri": 1, "due": "Wed"}, {"name": "Review", "pri": 2, "due": "Tue"}, {"name": "Plan", "pri": 1, "due": "Mon"}, ] # Pass 1: sort by due day tasks.sort(key=lambda t: ["Mon","Tue","Wed"].index(t["due"])) # Pass 2: sort by priority tasks.sort(key=lambda t: t["pri"])

Example 3: Tuple Key Shortcut

Instead of two passes, you can sort once using a tuple key. Python compares tuples element-by-element, giving you multi-key sorting in one step:

tasks.sort(key=lambda t: ( t["pri"], ["Mon","Tue","Wed"].index(t["due"]) ))

When Stability Doesn't Matter

Stability is irrelevant in certain situations. Recognising these cases helps you avoid over-engineering:

Unique Keys
If every element has a distinct sort key, no two elements are "equal", so stability has no effect.
Single Key
If you only care about one field and have no secondary ordering requirement, stability adds nothing observable.
Full Comparison
If the key function captures all fields (e.g., a tuple of every attribute), nothing is "equal" unless objects are identical.

Common Mistakes

✕ Wrong pass order
Sorting by the primary key first then the secondary key destroys the primary ordering. Always sort the least important key first.
✕ Assuming all sorts are stable
In other languages (C, C++, JavaScript), the default sort may not be stable. Python guarantees stability, but do not assume this is universal.
✕ Confusing sort key with equality
Two items can be "equal by sort key" but be completely different objects. Stability preserves order of those distinct items.

Summary at a Glance

Concept Key Point
Stable Sort Equal elements keep their original relative order
Python's sort Timsort: always stable, \( O(n \log n) \) worst case
Multi-key sorting Sort least-important key first, most-important last
Tuple key key=lambda x: (primary, secondary) in one pass
When irrelevant Unique keys or single-criteria sorts
Unstable sorts Quicksort, Heapsort: may swap equal elements

Question 1 of 5

A sorting algorithm is called stable when:

Question 2 of 5

Given the input [(2,"x"), (1,"y"), (2,"z")], what is the result of sorted(data, key=lambda t: t[0])?

Question 3 of 5

To sort a list first by department (primary) then by hire date (secondary) using two successive sort() calls, which order should you sort in?

Question 4 of 5

Which of the following algorithms is NOT stable?

Question 5 of 5

When does stability have no observable effect on the sorted output?