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))
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 thecmp()
functionality, you could use the expression(a > b) - (a < b)
as the equivalent forcmp(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'