What is functools.cmp_to_key in Python?

What is the functools module in Python?

The functools module in Python allows us to create higher-order functions that interact with other functions. The higher-order functions either return other functions or operate on them to broaden the scope of the function without modifying or explicitly defining them.

Key function

A callable that returns a value for sorting or ordering is known as a key function or a collation function. A lot of Python functions accept key functions to modify the order or grouping of items. For example, min(), max() etc. A key function takes an argument and returns a value that’s considered as the sort key.

Comparison function

Any callable that performs the following is called a comparison function.

  1. Accepts two arguments.
  2. Compares the two arguments.
  3. Returns
    1. A negative value indicating the first argument is lesser than the second argument.
    2. A positive value indicating the first argument is greater than the second argument.
    3. A zero indicates the first argument is equal to the second argument.

cmp_to_key function

Python 2 that has reached End of Life supported comparison functions. But now, the comparison functions are deprecated and no longer used. Hence, cmp_to_key is introduced in Python 3 to support the comparison functions in the form of key functions.

Syntax

functools.cmp_to_key(callable)

The function takes a callable as a parameter.

Code

from filecmp import cmp
from functools import cmp_to_key
import random
def compare(x, y):
if x==y: return 0
return 1 if x > y else -1
randomlist = random.sample(range(10, 30), 5)
print("List before sorting - ", randomlist)
randomlist.sort(key=cmp_to_key(compare))
print("List after sorting - ", randomlist)

Code explanation

  • Lines 1–3: We import the relevant classes and functions.
  • Lines 6–8: We define a comparison function called compare.
  • Line 11: A list of random values ranging from 10 to 30 is generated. The generated list is called randomlist.
  • Line 12:randomlist is printed before sorting.
  • Line 15: randomlist is sorted using the sort() method, passing the compare function as the parameter to cmp_to_key.
  • Line 16: The sorted randomlist is printed.

Free Resources