Skip to main content

cmp_to_key

cmp_to_key turns a two-argument comparator (negative / zero / positive) into a key= for sorted, list.sort, min and max. Use it when the order depends on comparing two items together and can't be expressed as a single key, e.g. "Largest Number".

Syntax​

from functools import cmp_to_key

def cmp(a: int, b: int) -> int:
return -1 if a < b else (1 if a > b else 0) # negative: a first

sorted([3, 1, 2], key=cmp_to_key(cmp)) # -> [1, 2, 3] O(n log n)

Largest Number (LC 179)​

from functools import cmp_to_key

def largest_number(nums: list[int]) -> str:
strs = list(map(str, nums))

def cmp(a: str, b: str) -> int:
if a + b > b + a:
return -1 # a goes first
if a + b < b + a:
return 1
return 0

strs.sort(key=cmp_to_key(cmp))
res = "".join(strs)
return "0" if res[0] == "0" else res # all zeros -> "0"

largest_number([3, 30, 34, 5, 9]) # -> '9534330'

Subtraction comparator for numbers​

from functools import cmp_to_key

pts = [(1, 2), (1, -1), (0, 5)]
# x ascending, then y descending
sorted(pts, key=cmp_to_key(lambda a, b: (a[0] - b[0]) or (b[1] - a[1])))
# -> [(0, 5), (1, 2), (1, -1)]
# prefer a tuple key when possible: sorted(pts, key=lambda p: (p[0], -p[1]))

With min / max​

from functools import cmp_to_key

words = ["bb", "a", "ccc"]
max(words, key=cmp_to_key(lambda a, b: len(a) - len(b))) # -> 'ccc'

Docs​