Explain the result of a stable sort

Type one expression at a time and check its delimiters. · 158 words

A stable sort keeps equal-key records in their original relative order. A sort key is the value compared. A key function selects it from each record. For an AI leaderboard, use runs = [('r1', 0.91, 'A'), ('r2', 0.91, 'B'), ('r3', 0.88, 'C'), ('r4', 0.91, 'D')]. The command runs.sort(key=lambda run: run[1], reverse=True) puts higher accuracy first but ignores the ID and label when comparing scores. Those extra fields remain attached to each result.

The sorted list is [('r1', 0.91, 'A'), ('r2', 0.91, 'B'), ('r4', 0.91, 'D'), ('r3', 0.88, 'C')]. The three records tied at 0.91 keep their input order: r1, r2, then r4. Stability does not alphabetize ties or choose them randomly. It preserves their prior order. This remains true with reverse=True in Python. That behavior is useful for model submissions or search results because an equally scored later result does not jump ahead of an earlier one. The sort method changes the list in place and returns None.

Check your recall

If ('r5', 0.91, 'E') is inserted at the end before sorting, where will it appear among the 0.91 runs, and why?

Check your answer

It will appear after r4, making the tied order r1, r2, r4, r5. The stable sort preserves the original relative order of records with equal accuracy.

Sources and credits

Original KeyTouch lesson. Background reading · Python Software Foundation · The Python Tutorial.