Adapt a two-argument comparison function for key-based sorting.
What You Will Learn
cmp_to_key converts a legacy comparator returning negative, zero, or positive values into objects accepted by key= in sorted() or list.sort(). Direct key functions are often clearer and faster.
Step-by-Step Example
The example below makes the behavior visible with small input values that you can change safely.
from functools import cmp_to_key
def compare_lengths(left, right):
return (len(left) > len(right)) - (len(left) < len(right))
words = ['pear', 'fig', 'watermelon']
print(sorted(words, key=cmp_to_key(compare_lengths)))
How the Example Works
- The imports provide the standard-library tools used in the demonstration: functools.
- The function compare_lengths defines reusable behavior; its body executes when it is called, not when it is declared.
- The variable words holds the result of ['pear', 'fig', 'watermelon']. Later lines use that value or inspect how it changes.
- The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.
For the chosen input, the expression sorted(words, key=cmp_to_key(compare_lengths)) prints ['fig', 'pear', 'watermelon']. Compare that result with the rule above before you change the argument.
Expected output from the example:
['fig', 'pear', 'watermelon']
When You Would Use This
These tools are useful when composing small reusable functions, adapting callbacks, or eliminating repeated work. Pay attention to whether the operation returns a new object, updates state, or produces lazy results. Test a small success case and a boundary case before integrating it into an application.
Practice: Modify the Code
Rewrite a comparator as a direct key function and compare clarity.
Verify the changed output against the behavior described above, including the relevant invalid or boundary case.
For complete parameters and version details, consult the official Python documentation.
Common Beginner Mistakes
- Returning a boolean comparator instead of a negative, zero, or positive ordering result.
- Using a wrapper without checking which original function, arguments and return values it preserves.
Key Takeaways
- Adapt a two-argument comparison function for key-based sorting.
- cmp_to_key converts a legacy comparator returning negative, zero, or positive values into objects accepted by key= in sorted() or list.sort().
- Apply this operation only after checking the assumptions and input conditions shown in the example.