Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use cmp() in Python 3?

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] 
like image 972
BenFire Avatar asked Mar 18 '14 20:03

BenFire


People also ask

How do I use CMP in Python 3?

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.

What is __ cmp __ Python?

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.

What is CMP function?

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.

Why did python remove CMP?

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


1 Answers

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.

like image 150
DSM Avatar answered Oct 14 '22 14:10

DSM