Comparing Objects in Python (cmp())

The cmp() built-in function CoMPares two objects, say, obj1 and obj2, and returns a negative number (integer) if obj1 is less than obj2, a positive number if obj1 is greater than obj2, and zero if obj1 is equal to obj2. Notice the similarity in return values as C’s strcmp(). The comparison used is the one that applies for that type of object, whether it be a standard type or a user-created class; if the latter, cmp() will call the class’s special __cmp__() method.

Example

>>> a,b = -4,12
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = -4
>>> cmp(a,b)
0
>>> a,b = 'abc','xyz'
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = 'abc'
>>> cmp(a,b)
0