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.
- Accepts two arguments.
- Compares the two arguments.
- Returns
- A negative value indicating the first argument is lesser than the second argument.
- A positive value indicating the first argument is greater than the second argument.
- 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 cmpfrom functools import cmp_to_keyimport randomdef compare(x, y):if x==y: return 0return 1 if x > y else -1randomlist = 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:
randomlistis printed before sorting. - Line 15:
randomlistis sorted using thesort()method, passing thecomparefunction as the parameter tocmp_to_key. - Line 16: The sorted
randomlistis printed.