Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python sorting: stable keys, independent output and explicit tie rules

Last updated: 30 Sept 20264 min read
tutorial
IntermediateBy AITrove Editorial

Python sorted creates an ordered list, while list.sort changes an existing list and returns None.

Download Python source kit

Operation contract

The import queues receipts by minor-unit amount. Two equal amounts retain their incoming order; this is intentional because the input already records arrival order. The fixture prints the original sequence to show that sorted leaves its outer ordering intact, then sorts that owned input by identifier and records the returned None. Sorting the input has to be allowed by its owner.

Failure and ownership boundary

Equal keys do not magically mean identical business records. If the input order is nondeterministic and the output must be reproducible, include a declared identifier tie-breaker. Keys must be comparable; a missing amount or a mixture of text and integers needs validation first. The output still refers to the same row objects, so it is not an immutable snapshot. Python heapq top-k: define ties before ranking frequencies avoids sorting all records when only a small ranked subset is needed.

Working program

python
receipts = [(43, 125), (41, 75), (42, 75)]
ranked = sorted(receipts, key=lambda receipt: receipt[1])
print(ranked)
print(receipts)
result = receipts.sort(key=lambda receipt: receipt[0])
print(result)
print(receipts)

Output

Output
[(41, 75), (42, 75), (43, 125)]
[(43, 125), (41, 75), (42, 75)]
None
[(41, 75), (42, 75), (43, 125)]

Costs and limits

Comparison sorting has O(n log n) worst-case comparison work for this list of bounded keys. sorted retains O(n) output entries; in-place sorting may also need O(n) working storage. An expensive key function adds its own per-record cost.

Common Mistakes

  • Do not assign the None result of list.sort as the ordered list.
  • Specify tie behavior when arrival order is not reliable.

Connected lessons

Python closures: capture loop values at the intended time, Python heapq top-k: define ties before ranking frequencies, Python lists: slicing copies the outer sequence, not nested objects.

Apply this boundary

Python merge sort: stable ordering without editing the input.

Follow the related contract

Python bisect: binary position search does not make list insertion logarithmic, Python lambda functions: one expression and the same closure rules.

python
sorting
Storage details