Python cmp-to-key()
The cmp_to_key() function from functools is a higher-order function that converts an old-style comparison function into a key function usable with tools like sorted(), min(), or max(). A comparison function is any callable that takes two arguments and returns:
- A negative number if the first argument is less than the second,
- A positive number if the first argument is greater,
- Or zero if they are equal.
A key function, by contrast, takes a single argument and returns a value to be used as a sorting key. cmp_to_key() is especially useful when migrating code from Python 2 (which supported comparison functions) to Python 3 (which only supports key functions).
Syntax
The cmp-to-key() function is part of the functools module:
from functools import cmp_to_key
functools.cmp_to_key(comp_func)
Parameters:
comp_func: This is a function that takes two arguments and compares them, returning:
- A negative number, if the first value is less than the second
- A positive number, if the first value is more than the second
- Or zero, if both values are equal
Return value:
Returns a key function that can be used as the key argument in sorting functions like sorted(), list.sort(), min(), or max().
Example 1
This example demonstrates checking which of two values is heavier (larger) using cmp_to_key():
from functools import cmp_to_key# Create a list of numbersweights = [20, 200, 10, 1]# Define the comparison functiondef lighter_to_heavier(a: float, b:float):if a == b: return 0return 1 if a > b else -1# Reorganize the list from smallest to largestprint("Unsorted weights", weights)weights.sort(key=cmp_to_key(lighter_to_heavier))print("Sorted weights", weights)
The output of this code is:
Unsorted weights [20, 200, 10, 1]Sorted weights [1, 10, 20, 200]
Example 2
This example reorganizes the list from largest to smallest by modifying the comparison function:
from functools import cmp_to_key# Create a list of numbersweights = [20, 200, 10, 1]# Define the comparison functiondef heaviest_to_smallest(a: float, b: float):if a == b: return 0return 1 if a < b else -1# Reorganize the list from largest to smallestprint("Unsorted weights", weights)weights.sort(key=cmp_to_key(heaviest_to_smallest))print("Sorted weights", weights)
The output of this code is:
Unsorted weights [20, 200, 10, 1]Sorted weights [200, 20, 10, 1]
Codebyte Example: Reorganize a list of strings by length
This example shows sorting strings by their length using a comparison function converted with cmp_to_key():
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours