Ch. 9 · Python

Python Stable Sorting and Key Functions

Python Stable Sorting and Key Functions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readintermediateupdated Oct 3, 2026

Python sorting is stable: equal keys retain their prior order. A key function separates ordering criteria from the records themselves.

Before you start

You should know Python functions, collections and exceptions. Use a small isolated script or interactive session to trace the example. Pay attention to when objects are created and when work executes; iteration, binding and mutation can happen at different points in a program.

The practical goal is to reason through this situation: Sort employees by department while preserving an earlier name order within equal departments. Read the walkthrough first, then try the interview exercise before opening its answer. The important part is explaining the decision and its consequences, rather than remembering a definition alone.

Step-by-step walkthrough

Step 1: State all ordering criteria

Department and name can be represented as a tuple key.

Step 2: Handle missing values

Choose an explicit ordering policy rather than comparing incompatible missing and string values.

Step 3: Use stability intentionally

Equal sort keys preserve prior order, enabling deliberate multi-pass sorting.

Worked scenario

Sort employees by department while preserving an earlier name order within equal departments.

rows = [('B', 'Ada'), ('A', 'Zoe'), ('A', 'Lin')]
print(sorted(rows, key=lambda row: (row[0], row[1])))
# [('A', 'Lin'), ('A', 'Zoe'), ('B', 'Ada')]
python

For two-pass sorting, sort the secondary criterion first and primary criterion second; stability retains the established secondary ordering within equal primary keys.

Common mistake

Repeated expensive work inside comparison logic can dominate sorting time.

Verify the behavior

Test ties, missing fields and already-sorted input; verify multi-pass and tuple-key results agree under the chosen policy.

Interview exercise

Order by department then name.

Answer and reasoning

Use a tuple key or deliberately exploit stability across ordered passes, stating how missing values are handled.

Continue learning

Compare the scenario with the Python interview questions and test your understanding with the Python MCQs. For terminology and implementation details, consult the reference material.

More in Python

read ✓Python · hard

Python asyncio.gather and Timeouts

Run coroutines concurrently with asyncio.gather, enforce timeouts, and handle partial failures and cancellation correctly.

~2 min readread →
read ✓Python · mid

Python Bounded Async Worker Queues

Use asyncio.Queue and a fixed worker pool to bound pending work. Trace backpressure, shutdown and failure ownership.

~3 min readread →
read ✓Python · mid

Python Asyncio and Blocking Functions

Python Asyncio and Blocking Functions. Learn the reasoning, a practical example, common mistakes and an interview exercise.

~2 min readread →
esc