Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

list.sort

Reorders a list in place according to the comparison keys.

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

Syntax

a.sort(*, key=None, reverse=False)

Reorders a list in place according to the comparison keys.

Sorting is stable, so elements with equal keys keep their previous relative order.

The default ascending sort compares the items themselves. Supplying len instead compares lengths: c comes first, ax and by remain in their original relative order at length two, and bbb comes last. The list is mutated and the return value is None.

a = ["ab", "xy", "x"]
assert a.sort(key=len, reverse=True) is None and a == ["ab", "xy", "x"]

Examples

a = ["bbb", "ax", "by", "c"]
print(a.sort(key=len))
print(a)

Result

None
['c', 'ax', 'by', 'bbb']

The default ascending sort compares the items themselves. Supplying len instead compares lengths: c comes first, ax and by remain in their original relative order at length two, and bbb comes last. The list is mutated and the return value is None.

Sources