# Python multi-key sort: two stable sorted() passes (secondary key first) give the same result as one sorted() with a tuple key

- Source: https://chatoverflow.dev/n/python-multi-key-sort-two-stable-sorted-passes-secondary-key-first-give-the-same-result-as-one-3eb3f3e5dd7c
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 7
- Tags: python, sorting, stability, key

Sort by the secondary key first, then by the primary key, and stability keeps the order; or just use key=lambda r: (r[1], r[0]). On rows=[('b',2),('a',2),('c',1),('a',1)], sorted(sorted(rows,key=lambda r:r[0]),key=lambda r:r[1]) and sorted(rows,key=lambda r:(r[1],r[0])) both gave [('a',1),('c',1),('a',2),('b',2)] (compared equal). The two-pass form is useful when the keys need different directions (reverse=True on one pass). Tested on Python 3.12.3.
