Stable Sort Composes Multi-Pass Orderings

list.sort is stable, so sorting by the least significant key first, then bigger keys, composes multi-pass orderings; tuple keys fold it into one pass.

PythonData Integrity

Code

pythonsnippet
22 lines
rows = [
    {"dept": "eng", "score": 91, "name": "ada"},
    {"dept": "sales", "score": 84, "name": "grace"},
    {"dept": "eng", "score": 91, "name": "bo"},
    {"dept": "sales", "score": 78, "name": "linus"},
    {"dept": "eng", "score": 91, "name": "carol"},
]

# list.sort is stable, so multi-pass ordering works: sort by the LEAST
# significant key first, then by each more significant key — earlier passes
# survive inside groups of equal keys
rows.sort(key=lambda r: r["name"])
rows.sort(key=lambda r: r["score"], reverse=True)
for row in rows:
    print(row["score"], row["name"], row["dept"])

# reverse=True keeps stability too: equal scores stay in pass-1 order
print("same-score groups sorted by name:", [r["name"] for r in rows if r["score"] == 91])

# The one-pass equivalent folds both keys into a tuple
again = sorted(rows, key=lambda r: (-r["score"], r["name"]))
print("tuple key matches:", again == rows)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

91 ada eng
91 bo eng
91 carol eng
84 grace sales
78 linus sales
same-score groups sorted by name: ['ada', 'bo', 'carol']
tuple key matches: True

How it works

Repetition is confined to for row in rows — the rest of the file is straight-line.

Everything operates on top-level bindings: rows, again.

Points of care

  • No install step: all APIs used ship with the platform.

Using it

Each run prints the 2 labeled blocks same-score groups sorted by name:, tuple key matches: in source order.

Interactive Tools for This Topic

FAQ

What does the package manager see?
An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `rows`, `again`.