Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

functools.cmp_to_key

Adapts a two-argument comparison function for a sorting interface that expects single-argument keys.

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

Syntax

functools.cmp_to_key(func)

Adapts a two-argument comparison function for a sorting interface that expects single-argument keys.

The comparator must return a negative, zero or positive value consistently. Tied keys retain their original order during sorting.

Wrap a two-argument comparator to serve as a one-argument sort key. The wrapper's comparisons call the comparator, interpreting negative as less, zero as tied and positive as greater. sorted is stable, so the equal-length strings cc and aa remain in their input order. This adapter is useful for an existing comparison API such as locale.strcoll.

from functools import cmp_to_key
K = cmp_to_key(lambda a, b: len(a)-len(b))
assert K("x") < K("zz") and K("aa") == K("bb")
assert sorted(["bb", "a", "cc"], key=K) == ["a", "bb", "cc"]

Examples

import functools
def compare(a, b):
    return len(a) - len(b)

print(sorted(["bbb", "cc", "aa", "d"], key=functools.cmp_to_key(compare)))

Result

['d', 'cc', 'aa', 'bbb']

Wrap a two-argument comparator to serve as a one-argument sort key. The wrapper's comparisons call the comparator, interpreting negative as less, zero as tied and positive as greater. sorted is stable, so the equal-length strings cc and aa remain in their input order. This adapter is useful for an existing comparison API such as locale.strcoll.

Sources