The cmp () function
The cmp (x, y) function compares the values of two arguments x and y:
cm (x, y)
Returned value:
Negative number if x is less than y.
Zero if x equals y.
A positive number if x is greater than y.
The built-in cmp () function usually returns only -1 values , 0, or 1. However, there are other places where functions with the same calling sequence are expected, and these functions may return different values. It is best to observe only the result sign.
""" cmp (2.8) -1""" cmp (6.6) 0""" cmp (4.1) 1""" cmp (’stackexchange’,’ stackoverflow’) -1
The cmp () method compares the elements of two lists.
Syntax
cmp (list1, list2)
If elements are of the same type, do the comparison and return the result. If the elements are of different types, check if they are numbers.
If numbers, cast numerically if necessary and compare.
If one of the elements is a number, then the other is " large "(the numbers are the" smallest ").
Otherwise, the types are sorted alphabetically by name.
If we reach the end of one of the lists, the longer list will be“ larger ". If we exhaust both lists and use the same data, the result is equality, which means that 0 is returned.
example
The following example shows the use of the cmp () method.
list1, list2 = [456, ’xyz’], [789,’ abc’] print cmp (list1, list2) print cmp ( list2, list1) list3 = list2 + [896]; print cmp (list2, list3)
When we run the above program, it produces the following output &
- 1 1 -1