Python cmp() function

2k Views Asked by At

Hello I was trying to compare two tuples in python using the cmp() function But there was an error wich is the following:

NameError: name 'cmp' is not defined

my Code:

myStupidTup = ("test",10,"hmm",233,2,"am long string")
mySmartTup = ("test",10,233,2)
print(cmp(myStupidTup, mySmartTup)) 
1

There are 1 best solutions below

0
On BEST ANSWER

The cmp function is only in Python 2.x. As mentioned in the official Python documentation:

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).)

The cmp equivalent in Python 3.x is:

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

Note: Your tuples (myStupidTup and mySmartTup) don't support comparison. You will get a TypeError if you run it: TypeError: '>' not supported between instances of 'str' and 'int'