Use stable sorting to preserve an earlier order among equal-key records.
What You Will Learn
Python sorted() and list.sort() are stable: records with equal sort keys keep their relative order. This enables multi-stage sorting, such as sorting by name first and then by department. You can also use a tuple key for many cases; stability becomes especially useful when stages have different sort directions.
Time complexity assumes a specific input structure. Include setup work such as sorting or building a lookup table when comparing complete solutions.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
workers = [
("Ada", "Support"),
("Ben", "Sales"),
("Carl", "Support"),
]
alphabetic = sorted(workers, key=lambda row: row[0])
by_department = sorted(alphabetic, key=lambda row: row[1])
print(by_department)
How the Example Works
- The variable workers holds the result of [('Ada', 'Support'), ('Ben', 'Sales'), ('Carl', 'Support')]. Later lines use that value or inspect how it changes.
- The variable alphabetic holds the result of sorted(workers, key=lambda row: row[0]). Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression by_department prints [('Ben', 'Sales'), ('Ada', 'Support'), ('Carl', 'Support')]. Compare that result with the rule above before you change the argument.
Expected output from the example:
[('Ben', 'Sales'), ('Ada', 'Support'), ('Carl', 'Support')]
When You Would Use This
This technique matters when a program handles larger queues, sorted records, or repeated lookups. Choose the data structure based on actual operations and the preconditions the algorithm requires. Verify boundary inputs before optimizing for speed.
Practice: Modify the Code
Add another Support employee and verify how their relative order is preserved.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Assuming sorting by department randomly reorders people from the same department.
- Sorting by the minor key after sorting by the major key and losing the intended priority.
Key Takeaways
- Use stable sorting to preserve an earlier order among equal-key records.
- Python sorted() and list.sort() are stable: records with equal sort keys keep their relative order.
- Apply this operation only after checking the assumptions and input conditions shown in the example.