Open In App

How does the functools cmp_to_key function works in Python?

Last Updated : 12 Nov, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

There has been a change in Python’s sorted() function, it now takes three values namely, the iterable, key, and reverse. Out of these last two are optional but this article emphasizes the key part of the sorted() function. What key does is, it helps in the comparison of iterable elements while sorting.  Python already had cmp() function that used to compare two values and return 1, -1, or 0. But as of Python 3.0 and above, this function has been deprecated and a new function cmp_to_key() has been introduced. The following article discusses the application and explanation of this function.

Definition

  • cmp_to_key() uses a key to compare elements
  • It is built into functools module, thus functools has to be imported first in order to use the function
  • Used with tools that accept key functions such as min(), max(), sorted() etc.
  • Takes only one argument which strictly should be a callable
  • This function returns a special key that can be used to compare elements

Syntax:

functools.cmp_to_key(callable)

Explanation

  • Each element is compared with every other element of the list until a sorted list is obtained
  • Every element apparently calls mycmp() function with the other element of the list
  • mycmp() function returns a key after comparing the numbers
  • This key is eventually helping sorted() to arrange elements in ascending order

Below is the Implementation.

Example 1: Program that sorts a list using a key provided by cmp_to_key() function

Python3




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]

Example 2: Program that prints maximum and minimum numbers from a list using key provided by cmp_to_key() function

Python3




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(min([45, 78, 813], key=functools.cmp_to_key(mycmp)))
print(max([45, 78, 813], key=functools.cmp_to_key(mycmp)))


Output:

comparing  78  and  45
comparing  813  and  45
45
comparing  78  and  45
comparing  813  and  78
813


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads