Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Sorting and comparison

Sort records by a key that is computed once per input element.

Version: Python 3.14; repository image, production runtime not attested

Syntax

sorted(records, key=lambda record: record[1])

Sort records by a key that is computed once per input element.

Sorting is stable, so records with equal keys retain their input order even for reverse sorting. The function sorted returns a new list, whereas list.sort mutates its list and returns None.

Keys must support the required comparisons or sorting can raise TypeError.

Examples

rows = [("B", 2), ("A", 2), ("C", 1)]
calls = []
def key(row):
    calls.append(row[0])
    return row[1]
print([r[0] for r in sorted(rows, key=key, reverse=True)], len(calls))
print(rows.sort(key=lambda r: r[1]), [r[0] for r in rows])
try:
    sorted([None, 1])
except TypeError:
    print("incomparable")

Result

['B', 'A', 'C'] 3
None ['C', 'B', 'A']
incomparable

Keys must support the required comparisons or sorting can raise TypeError.

Sources