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.
Code
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: TrueHow 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
JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.