I cannot get the command cmp()
to work.
Here is the code:
a = [1,2,3] b = [1,2,3] c = cmp(a,b) print (c)
I am getting the error:
Traceback (most recent call last): File "G:\Dropbox\Code\a = [1,2,3]", line 3, in <module> c = cmp(a,b) NameError: name 'cmp' is not defined [Finished in 0.1s]
cmp() does not work in python 3. You might want to see list comparison in Python. Practical Application: Program to check if a number is even or odd using cmp function. Approach: Compare 0 and n%2, if it returns 0, then it is even, else its odd.
The __cmp__() special method is no longer honored in Python 3. In Python 2, __cmp__(self, other) implemented comparison between two objects, returning a negative value if self < other , positive if self > other , and zero if they were equal.
The cmp() function The cmp(x,y) function compares the values of two arguments x and y − cmp(x, y) The return value is − A negative number if x is less than y. Zero if x is equal to y.
cmp was removed because the key attribute to . sort() and sorted() is superior in most cases. It was a hold-over from C more than anything, and was confusing to boot. Having to implement a separate __cmp__ method next to the rich comparison operators ( __lt__ , __gt__ , etc.)
As mentioned in the comments, cmp
doesn't exist in Python 3. If you really want it, you could define it yourself:
def cmp(a, b): return (a > b) - (a < b)
which is taken from the original What's New In Python 3.0. It's pretty rare -- though not unheard of -- that it's really needed, though, so you might want to think about whether it's actually the best way to do whatever it is you're up to.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With