-1

Is there a simple function available that compares numbers x and y and returns -1 when x is less than y, 1 when x is more than y and 0 when they're equal?

If not what is the shortest way to do so?

FireFuro99
  • 357
  • 1
  • 5
  • 18

1 Answers1

10

There was a cmp() method in Python2 that could do exactly what you require, however it was discontinued in Python 3. You can create this method likewise:

def compare(a, b):
    return (a > b) - (a < b) 

It has been mentioned in the documentation here.

The cmp() function should be treated as gone, and the cmp() special method is no longer supported. Use lt() for sorting, eq() with hash(), and other rich comparisons as needed. (If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)

Shivam Roy
  • 1,961
  • 3
  • 10
  • 23
  • 1
    Why was it discontinued, seems useful to me? But that's a nice way to implement it, better than with 3 ifs as i (and Axe319) would've done it, thanks – FireFuro99 Sep 29 '21 at 14:37
  • 3
    @FireFuro99 because it is rarely needed, and when it is needed it's very easy to implement as you can see – DeepSpace Sep 29 '21 at 14:39