Python List cmp() Method



The Python List cmp() method compares elements of two lists. These lists can be comprised of elements in either similar or different data types. If elements are of the same type, this method compares them lexicographically and returns the result; but if elements are of different types, it checks the different cases of comparison. They are as follows −

  • If the elements are numbers, perform numeric coercion if necessary and compare.
  • If either element is a number, then the other element is considered "larger" (numbers are "smallest").
  • Otherwise, types are sorted alphabetically by name.
  • If we reached the end of one of the lists before the other list, the longer list is "larger."

Note: This method is only executable in Python 2.x and does not work in Python 3.x.

Syntax

Following is the syntax for the Python List cmp() method −

cmp(list1, list2)

Parameters

  • list1 − This is the first list to be compared.

  • list2 − This is the second list to be compared.

Return Value

The method returns 1 if the first list is greater than the second list and -1 if its smaller; 0 is returned when both the lists are equal.

Example

The following example shows the usage of the Python List cmp() method. This program executes only in Python 2.x versions.

list1, list2 = [123, 'xyz'], [456, 'abc']
print cmp(list1, list2)
print cmp(list2, list1)
list3 = list2 + [786];
print cmp(list2, list3)

When we run above program, it produces following result −

-1
1
-1

Example

If the user wants to execute this method in the Python 3.x interpreter, they can declare a user-defined function as shown in the given example. This method works similar to the built-in cmp() method.

def cmp(x, y):
   return (x > y) - (x < y)
#x > y
x = 5
y = 3
print("The cmp value for x>y is : ",cmp(x, y),"\n")
#x<y
x = 7
y = 9
print("The cmp value for x<y is : ",cmp(x, y),"\n")
#x=y
x = 13
y = 13
print("The cmp value for x=y is : ",cmp(x, y))
#odd and even
k = 16
if cmp(0, k % 2):
   print("\n","The given number",k,"is odd number ")
else:
   print("\n","The given number",k,"is even number")
k= 31
if cmp(0, k % 2):
   print("\n","The given number",k,"is odd number")
else:
   print("\n","The given number",k,"is even number")

Running the above code gives us the following result −

The cmp value for x>y is : 1

The cmp value for x<y is : -1

The cmp value for x=y is : 0

The given number 16 is even number

The given number 31 is odd number
python_lists.htm
Advertisements