Python cmp_to_key
last modified November 18, 2026 Python 3.15
In this article we show how to sort with comparison functions in Python
using functools.cmp_to_key. We port old comparator code, look
at how the key wrapper works, and find the cases where a comparator is the
simplest tool.
A comparison function, or comparator, takes two values and
returns a negative number if the first goes first, a positive number if the
second goes first, and zero if they are equal. Python 2 sorted with
comparators through the cmp parameter. Python 3 removed that
parameter and the built-in cmp function; sorting is done with
key functions. The cmp_to_key function, available
since Python 2.7 and 3.2, bridges the two.
Sorting with a comparator
The cmp_to_key function turns a comparator into something that
can be passed as the key argument.
from functools import cmp_to_key
def by_length(a, b):
"""Negative if a goes first, positive if b goes first, 0 if equal."""
return len(a) - len(b)
words = ['forest', 'sky', 'water', 'cup', 'a', 'ocean', 'blue']
print(sorted(words, key=cmp_to_key(by_length)))
print(sorted(words, key=cmp_to_key(by_length), reverse=True))
print(sorted(words, key=len))
The by_length comparator subtracts the lengths, so the result
is negative when a is shorter. The reverse
parameter works as with any key. The last line shows that a key function
gives the same result here. Equal elements keep their order in all three
cases, because the sort is stable.
$ python cmp_basic.py ['a', 'sky', 'cup', 'blue', 'water', 'ocean', 'forest'] ['forest', 'water', 'ocean', 'blue', 'sky', 'cup', 'a'] ['a', 'sky', 'cup', 'blue', 'water', 'ocean', 'forest']
The removed cmp parameter
Code written for Python 2 passes the comparator directly.
def by_length(a, b):
return len(a) - len(b)
words = ['forest', 'sky', 'water', 'cup']
print(sorted(words, cmp=by_length))
In Python 3, sorted and list.sort accept only
key and reverse, both as keyword arguments. The
fix is mechanical: replace cmp=by_length with
key=cmp_to_key(by_length).
$ python cmp_py2.py
Traceback (most recent call last):
File "/home/user/python/cmp_py2.py", line 7, in <module>
print(sorted(words, cmp=by_length))
~~~~~~^^^^^^^^^^^^^^^^^^^^^^
TypeError: sort() got an unexpected keyword argument 'cmp'
How the wrapper works
The value returned by cmp_to_key is a class-like callable. Calling
it wraps a value in an object whose comparison operators call the
comparator.
from functools import cmp_to_key
def by_length(a, b):
print(f' compare {a!r} with {b!r}')
return len(a) - len(b)
Key = cmp_to_key(by_length)
print(type(Key))
k1, k2 = Key('forest'), Key('sky')
print(type(k1))
print(k1.obj)
print('k1 < k2:', k1 < k2)
print('k1 > k2:', k1 > k2)
print(sorted(['sky', 'water', 'a'], key=Key))
Both Key and the wrapped values are
KeyWrapper objects, implemented in C. The obj
attribute holds the wrapped value. The expression k1 < k2
calls by_length(k1.obj, k2.obj) and checks whether the result is
negative; k1 > k2 checks whether it is positive. The sort
creates one wrapper per element and then calls the comparator for each
comparison, as the printed calls show.
$ python cmp_object.py <class 'functools.KeyWrapper'> <class 'functools.KeyWrapper'> forest compare 'forest' with 'sky' k1 < k2: False compare 'forest' with 'sky' k1 > k2: True compare 'water' with 'sky' compare 'a' with 'water' compare 'sky' with 'water' compare 'a' with 'water' compare 'a' with 'sky' ['a', 'sky', 'water']
Mixed sort directions
A comparator can combine several criteria, each in its own direction. We sort employees by department ascending, salary descending, and name ascending.
from functools import cmp_to_key
from operator import itemgetter
employees = [
('Anna', 'IT', 3200),
('Peter', 'Sales', 2800),
('Lucia', 'IT', 4100),
('Martin', 'Sales', 2800),
('Eva', 'HR', 2600),
('Jozef', 'IT', 3200),
]
def cmp(a, b):
return (a > b) - (a < b)
def by_dept_salary_name(e1, e2):
# department ascending, salary descending, name ascending
return (cmp(e1[1], e2[1])
or cmp(e2[2], e1[2])
or cmp(e1[0], e2[0]))
res1 = sorted(employees, key=cmp_to_key(by_dept_salary_name))
res2 = sorted(employees, key=lambda e: (e[1], -e[2], e[0]))
res3 = sorted(employees, key=itemgetter(0))
res3.sort(key=itemgetter(2), reverse=True)
res3.sort(key=itemgetter(1))
for e in res1:
print(e)
print(res1 == res2 == res3)
Python 3 has no built-in cmp function, so we define one; the
expression (a > b) - (a < b) is -1, 0, or 1. The
or chain moves to the next criterion only when the previous one
returns 0. Swapping the arguments, as in cmp(e2[2], e1[2]),
reverses the direction. The same order can be achieved with a tuple key that
negates the salary, or with three stable sorts from the least important key
to the most important one. All three results are equal.
$ python mixed_order.py
('Eva', 'HR', 2600)
('Lucia', 'IT', 4100)
('Anna', 'IT', 3200)
('Jozef', 'IT', 3200)
('Martin', 'Sales', 2800)
('Peter', 'Sales', 2800)
True
Descending strings
Negation works only for numbers. When a secondary key is a string that must be sorted in descending order, a comparator is the shortest solution.
from functools import cmp_to_key
books = [
('Python', 2021), ('Algorithms', 2019), ('Rust', 2021),
('Go', 2019), ('Django', 2021), ('Bash', 2020),
]
def cmp(a, b):
return (a > b) - (a < b)
def year_desc_title_desc(b1, b2):
return cmp(b2[1], b1[1]) or cmp(b2[0], b1[0])
for book in sorted(books, key=cmp_to_key(year_desc_title_desc)):
print(book)
try:
sorted(books, key=lambda b: (-b[1], -b[0]))
except TypeError as e:
print('TypeError:', e)
The books are sorted by year descending and, within a year, by title
descending. The tuple key with -b[0] fails, because strings do
not support the unary minus. The alternative without a comparator is two
stable sorts, here both with reverse=True.
$ python desc_strings.py
('Rust', 2021)
('Python', 2021)
('Django', 2021)
('Bash', 2020)
('Go', 2019)
('Algorithms', 2019)
TypeError: bad operand type for unary -: 'str'
Order defined by pairs
Some orders cannot be expressed as a key computed from one element, because they depend on both elements at once. A classic example is arranging numbers to form the largest possible number.
from functools import cmp_to_key
def concat_order(a, b):
"""a goes first if the concatenation a + b is larger than b + a."""
if a + b > b + a:
return -1
if a + b < b + a:
return 1
return 0
def largest_number(nums):
digits = sorted(map(str, nums), key=cmp_to_key(concat_order))
return ''.join(digits)
print(largest_number([3, 30, 34, 5, 9]))
print(largest_number([10, 2]))
print(largest_number([121, 12]))
print(''.join(sorted(map(str, [3, 30, 34, 5, 9]), reverse=True)))
The number a goes before b if the concatenation
a + b is larger than b + a. For 3 and
30, 330 beats 303, so
3 goes first. The concatenated strings have the same length, so
their string comparison is a numeric one. Sorting the strings in reverse
order is not enough: it puts 30 before 3 and
produces a smaller number.
$ python largest_number.py 9534330 210 12121 9534303
Locale-aware sorting
The default string sort compares Unicode code points, which is wrong for
most languages. The locale module offers
strcoll, a comparator, and strxfrm, a key function.
import locale
from functools import cmp_to_key
locale.setlocale(locale.LC_COLLATE, 'sk_SK.UTF-8')
words = ['hora', 'chlieb', 'čaj', 'cesta', 'auto', 'zebra', 'ďateľ', 'dom',
'šál', 'strom', 'ihla', 'Žilina', 'Cyprus']
print(sorted(words))
print(sorted(words, key=cmp_to_key(locale.strcoll)))
print(sorted(words, key=locale.strxfrm))
We set the collation to Slovak. The plain sort puts the capitalized
Cyprus first and all words with diacritics at the end. With the
Slovak collation, č follows all words with c,
the digraph ch is a separate letter after h, and
upper and lower case are sorted together. Both functions give the same
result. Prefer strxfrm: it transforms each word once, while
strcoll is called for every comparison. The locale must be
installed on the system, otherwise setlocale raises
locale.Error.
$ python locale_sort.py ['Cyprus', 'auto', 'cesta', 'chlieb', 'dom', 'hora', 'ihla', 'strom', 'zebra', 'čaj', 'ďateľ', 'šál', 'Žilina'] ['auto', 'cesta', 'Cyprus', 'čaj', 'ďateľ', 'dom', 'hora', 'chlieb', 'ihla', 'strom', 'šál', 'zebra', 'Žilina'] ['auto', 'cesta', 'Cyprus', 'čaj', 'ďateľ', 'dom', 'hora', 'chlieb', 'ihla', 'strom', 'šál', 'zebra', 'Žilina']
Other functions with a key
The wrapper works everywhere a key function is accepted.
import bisect
import heapq
from functools import cmp_to_key
def by_length(a, b):
return len(a) - len(b)
Key = cmp_to_key(by_length)
words = ['forest', 'sky', 'water', 'cup', 'ocean', 'blue']
print(min(words, key=Key))
print(max(words, key=Key))
print(heapq.nsmallest(3, words, key=Key))
ordered = sorted(words, key=Key)
print(ordered)
pos = bisect.bisect_left(ordered, Key('tree'), key=Key)
print(pos)
The min, max, and heapq.nsmallest
functions take the same key argument as
sorted. The bisect functions accept
key since Python 3.10; the key is applied to the list elements
but not to the searched value, so we wrap 'tree' ourselves. A
four-letter word belongs at index 2.
$ python other_uses.py sky forest ['sky', 'cup', 'blue'] ['sky', 'cup', 'blue', 'water', 'ocean', 'forest'] 2
Inconsistent comparators
A comparator must define a consistent order: if a goes before
b and b before c, then
a must go before c. Python does not check this.
from functools import cmp_to_key
beats = {('rock', 'scissors'), ('scissors', 'paper'), ('paper', 'rock')}
def rps(a, b):
if (a, b) in beats:
return -1
if (b, a) in beats:
return 1
return 0
print(sorted(['rock', 'paper', 'scissors'], key=cmp_to_key(rps)))
print(sorted(['scissors', 'paper', 'rock'], key=cmp_to_key(rps)))
print(sorted(['paper', 'rock', 'scissors'], key=cmp_to_key(rps)))
In rock, paper, scissors every item beats another one, so there is no valid order. The sort does not raise an error; it returns some order that depends on the input. Comparators that use floating-point tolerances or random values break the rule in the same way.
$ python broken_cmp.py ['scissors', 'paper', 'rock'] ['scissors', 'paper', 'rock'] ['paper', 'rock', 'scissors']
Performance
A key function is called once per element. A comparator is called once per comparison, and every call goes through Python code.
import random
import timeit
from functools import cmp_to_key
random.seed(1)
words = [''.join(random.choices('abcdefgh', k=random.randint(1, 12)))
for _ in range(100_000)]
def by_length(a, b):
return len(a) - len(b)
tests = [
('key=len', lambda: sorted(words, key=len)),
('key=lambda', lambda: sorted(words, key=lambda w: len(w))),
('key=cmp_to_key', lambda: sorted(words, key=cmp_to_key(by_length))),
]
for name, fn in tests:
t = min(timeit.repeat(fn, number=1, repeat=5))
print(f'{name:15} {t * 1000:6.1f} ms')
We sort 100,000 random words by length. The built-in len as the
key is the fastest, and a lambda is a little slower. The comparator is about
six times slower than the key function. The sort makes about 750,000
comparisons, and each of them calls by_length. Use
cmp_to_key when a key is hard to write, not by default. The
times vary between runs and machines.
$ python benchmark.py key=len 8.6 ms key=lambda 10.2 ms key=cmp_to_key 51.9 ms
Source
functools.cmp_to_key – Python documentation
Sorting Techniques – Python documentation
locale.strxfrm – Python documentation
In this article we have sorted with comparison functions using
functools.cmp_to_key. See also
Python sort list,
Python sorted function,
Python Timsort, and
Python sorting algorithms compared.
Author
List all Python tutorials.