ML Foundations

Sort scores descending and names ascending in Python

Use stable sorting to order ranked records with different directions and predictable ties.

Example results for Sort scores descending and names ascending in Python. ranked: ('alpha', 3), ('beta', 2), ('beta', 2), ('delta', 2), ('gamma', 1)
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

One reverse flag reverses the whole key

A ranked report might require higher scores first and names in ascending order when scores tie. A tuple key with reverse=True reverses the ordering of the full tuple, including the name. A reader expecting alphabetical ties can therefore get the opposite order. Python sorts are stable: records with equal keys retain their earlier relative order. [1, 2]

This guide uses small Python tuples rather than a dataframe or a NumPy array. The first element is a name and the second is an integer score; the input order of records equal on both keys remains meaningful.

References: [1], [2]

Apply the less important key first

Run python examples/python_mixed_direction_sort.py. First sort by name in ascending order. Then stably sort that result by score in descending order. The score is now the primary key; within each equal-score group the earlier alphabetical ordering remains intact. [1]

The example also checks the equivalent single-pass key (-score, name), which works here because scores are numeric and can be negated. Both methods produce the same ordered records for the fixture. The duplicate beta records remain in their original relative order, although identical displayed values do not expose their identities. [1, 2]

sorted returns a new list, so the fixture checks that the first input record did not change. In contrast, list.sort modifies its list in place. Pick the behavior that matches ownership of the data. [1, 2]

Executed with Python 3.12.14; stdout and checksum are in private evidence.

rows = [("delta", 2), ("beta", 2), ("alpha", 3), ("beta", 2), ("gamma", 1)]

by_name = sorted(rows, key=lambda row: row[0])
ranked = sorted(by_name, key=lambda row: row[1], reverse=True)
single_pass = sorted(rows, key=lambda row: (-row[1], row[0]))
assert ranked == single_pass
assert ranked == [("alpha", 3), ("beta", 2), ("beta", 2), ("delta", 2), ("gamma", 1)]
print("ranked:", ranked)
print("input unchanged:", rows[0] == ("delta", 2))

Recorded output

ranked: [('alpha', 3), ('beta', 2), ('beta', 2), ('delta', 2), ('gamma', 1)]
input unchanged: True

References: [1], [2]

Define a tie policy for real data

If ties must be reproducible across independently ordered inputs, supply an additional unique identifier as a final key. Stability preserves input order for equal keys; it does not invent a consistent order between differently ordered inputs. [1]

This fixture assumes comparable strings and integer scores. Missing values, mixed incomparable types, locale-specific collation, and NaN scores need an explicit normalization or error policy before sorting. It measures no performance and does not prescribe a sorting method for arrays or distributed data.

References: [1], [2]

Sources

  1. Python sorting HOWTO
  2. Python sorted built-in