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')]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.