How does the functools cmp_to_key function works in Python?
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.
- 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
- 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
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
comparing 78 and 45 comparing 813 and 45 45 comparing 78 and 45 comparing 813 and 78 813