Quoted from the docs:
cmp(x, y)
Compare the two objects x and y and return an integer according to the outcome. The return value is negative if
x < y
, zero ifx == y
and strictly positive ifx > y
.
I was under the assumption that the return values are always -1
, 0
, and 1
but the docs don't explicitly say that, only mentioning zero and positive/negative return value.
Are there any situations when the return value of cmp(x,y)
is not -1
, 0
, or 1
?
The cmp() is part of the python standard library which compares two integers. The result of comparison is -1 if the first integer is smaller than second and 1 if the first integer is greater than the second. If both are equal the result of cmp() is zero.
from python wiki: In Py3. 0, the cmp parameter was removed entirely (as part of a larger effort to simplify and unify the language, eliminating the conflict between rich comparisons and the __cmp__ methods). The latter is very verbose and the same purpose is achieved in the former with just one line.
cmp() does not work in python 3.
cmp(list) is a method specified in Number in Python 2. The comparison of integral numbers have been discussed using cmp(). But many a times, there is a need to compare the entire list that can be composed of similar or different data types.
No, the docs explicitly say that yalues can be anything. The only value that is specified is 0
if the compared objects are equal. Don't trust the fact that you only see the values -1
, 0
and 1
, that's an implementation detail and could change*, so always check for <
and >
0.
*: note - actually, it won't really have a chance to change, since cmp
has gone away in pyhton3. use rich comparison instead.
Only 0 can be relied on, although the docstring for list.sort
is interesting:
print list.sort.__doc__
L.sort(cmp=None, key=None, reverse=False) -- stable sort *IN PLACE*;
cmp(x, y) -> -1, 0, 1
But in fact, sort doesn't actually impose this on it's comparison function as can be seen here:
def mycmp(a, b):
print "mycmp(): a - b = ", a - b
return a - b
L = [50, 30, 20, 40, 70, 50]
>>> L.sort(cmp=mycmp)
mycmp(): a - b = -20
mycmp(): a - b = -10
mycmp(): a - b = 20
mycmp(): a - b = 10
mycmp(): a - b = -10
mycmp(): a - b = 30
mycmp(): a - b = 20
mycmp(): a - b = 10
mycmp(): a - b = -20
mycmp(): a - b = 0
>>> print L
[20, 30, 40, 50, 50, 70]
Just for interest, but clearly sort
is working happily with values other than -1
, 0
, or +1
, so you should be too!
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