How does the functools cmp_to_key function works in Python
Last Updated :
22 May, 2025
functools.cmp_to_key() function converts an old-style comparison function (i.e., a function that compares two arguments and returns -1, 0, or 1) into a key function. This key function can then be used with sorting functions like sorted(), min() or max(). Example:
Python
import functools
def mycmp(a, b):
print("comparing ", a, " and ", b)
if a > b:
return 1
elif a < b:
return -1
else:
return 0
print(sorted([1, 2, 4, 2], key=functools.cmp_to_key(mycmp)))
Output
comparing 2 and 1
comparing 4 and 2
comparing 2 and 4
comparing 2 and 2
comparing 2 and 4
[1, 2, 2, 4]
Explanation:
- mycmp(a, b) to compare two values and print them, returning 1, -1, or 0 based on their order.
- sorted() with key=functools.cmp_to_key(mycmp) to sort the list [1, 2, 4, 2].
- mycmp runs multiple times during sorting, printing comparisons, then returns the sorted list.
Syntax
functools.cmp_to_key(func)
Parameter: func is a comparison function that takes two arguments and returns:
- a negative number if the first argument is less than the second,
- zero if they are equal,
- a positive number if the first is greater than the second.
Returns: A callable object that can be used as a key function for sorting.
How it Works?
Let's understand step-by-step how this function works.
- Define cmp(a, b): Write a function that compares two values and returns negative, zero or positive based on their order.
- Wrap items in a class: Create a helper class that uses cmp to define comparison methods like <, ==, etc.
- Sort using wrappers: Wrap the list items, sort them using sorted() or .sort(), then extract the original values if needed.
Examples
Example 1: Here, we compare strings based on their length and sort the list accordingly.
Python
import functools
def mycmp(a, b):
if len(a) > len(b):
return 1
elif len(a) < len(b):
return -1
else:
return 0
a = ["apple", "fig", "banana", "kiwi"]
res = sorted(a, key=functools.cmp_to_key(mycmp))
print(res)
Output['fig', 'kiwi', 'apple', 'banana']
Explanation: mycmp compares strings by length, returning 1, -1 or 0 if the first string is longer, shorter, or equal in length. sorted() uses functools.cmp_to_key to convert this into a key function for custom sorting.
Example 2: Here, we compare numbers in reverse order to find the minimum value based on that custom comparison.
Python
import functools
def mycmp(a, b):
if a > b:
return -1
elif a < b:
return 1
else:
return 0
a = [10, 2, 33, 5]
res = min(a, key=functools.cmp_to_key(mycmp))
print(res)
Explanation: mycmp compares numbers in reverse order, returning -1 if the first is greater, 1 if smaller and 0 if equal. The min() function uses functools.cmp_to_key to apply this comparison, effectively finding the maximum value according to this reversed order.
Example 3: Here, we compare numbers based on their remainder when divided by 5, then find the maximum value according to that custom comparison.
Python
import functools
def mycmp(a, b):
if (a % 5) > (b % 5):
return 1
elif (a % 5) < (b % 5):
return -1
else:
return 0
a = [12, 17, 5, 22, 14]
res = max(a, key=functools.cmp_to_key(mycmp))
print(res)
Explanation: mycmp compares numbers by their remainder mod 5, returning 1, -1, or 0 based on which remainder is larger, smaller or equal. max() uses functools.cmp_to_key to find the number with the highest remainder.
Related articles
Similar Reads
How does the functools cmp_to_key function works in Python?
functools.cmp_to_key() function converts an old-style comparison function (i.e., a function that compares two arguments and returns -1, 0, or 1) into a key function. This key function can then be used with sorting functions like sorted(), min() or max(). Example: Pythonimport functools def mycmp(a,
3 min read
Python | functools.wraps() function
functools is a standard Python module for higher-order functions (functions that act on or return other functions). wraps() is a decorator that is applied to the wrapper function of a decorator. It updates the wrapper function to look like wrapped function by copying attributes such as __name__, __d
4 min read
How to Add Function in Python Dictionary
Dictionaries in Python are strong, adaptable data structures that support key-value pair storage. Because of this property, dictionaries are a necessary tool for many kinds of programming jobs. Adding functions as values to dictionaries is an intriguing and sophisticated use case. This article looks
4 min read
How to use Function Decorators in Python ?
In Python, a function can be passed as a parameter to another function (a function can also return another function). we can define a function inside another function. In this article, you will learn How to use Function Decorators in Python. Passing Function as ParametersIn Python, you can pass a fu
3 min read
How to Define and Call a Function in Python
In Python, defining and calling functions is simple and may greatly improve the readability and reusability of our code. In this article, we will explore How we can define and call a function.Example:Python# Defining a function def fun(): print("Welcome to GFG") # calling a function fun() Let's unde
3 min read
How to Call a C function in Python
Have you ever came across the situation where you have to call C function using python? This article is going to help you on a very basic level and if you have not come across any situation like this, you enjoy knowing how it is possible.First, let's write one simple function using C and generate a
2 min read
How to bind arguments to given values in Python functions?
In Python, binding arguments to specific values can be a powerful tool, allowing you to set default values for function parameters, create specialized versions of functions, or partially apply a function to a set of arguments. This technique is commonly known as "partial function application" and ca
3 min read
How to Call Multiple Functions in Python
In Python, calling multiple functions is a common practice, especially when building modular, organized and maintainable code. In this article, weâll explore various ways we can call multiple functions in Python.The most straightforward way to call multiple functions is by executing them one after a
3 min read
How to Recall a Function in Python
In Python, functions are reusable blocks of code that we can call multiple times throughout a program. Sometimes, we might need to call a function again either within itself or after it has been previously executed. In this article, we'll explore different scenarios where we can "recall" a function
4 min read
Python | How to get function name ?
One of the most prominent styles of coding is following the OOP paradigm. For this, nowadays, stress has been to write code with modularity, increase debugging, and create a more robust, reusable code. This all encouraged the use of different functions for different tasks, and hence we are bound to
3 min read