Using the cmp function to get the comparison result of two objects
suggest changeSuppose you need to print 'greater than' if x > y, 'less than' if x < y and 'equal' if x == y.
['equal', 'greater than', 'less than'][(x > y) - (x < y)]
# x, y = 1, 1 output: 'equal'
# x, y = 1, 2 output: 'less than'
# x, y = 2, 1 output: 'greater than'
(x > y) - (x < y) returns the following values
| Comparison | Result |
|---|---|
x < y |
-1 |
x == y |
0 |
x > y |
1 |
cmp was removed in Python 3. The subtraction above is the same three-way result for values that support < and >. functools.cmp_to_key turns an old comparison function into a sort key. It does not return -1, 0, or 1.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents