Open In App

How does the functools cmp_to_key function works in Python

Last Updated : 22 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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.

  1. Define cmp(a, b): Write a function that compares two values and returns negative, zero or positive based on their order.
  2. Wrap items in a class: Create a helper class that uses cmp to define comparison methods like <, ==, etc.
  3. 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)

Output
33

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)

Output
14

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.


Practice Tags :

Similar Reads