Python List cmp() Method
Description
The cmp() method is used to compare elements of two lists.
Syntax
The syntax of the cmp() method is:
cmp(list1, list2)
Parameters
- list1 -- The list to be compared.
- list2 -- The list to be compared.
Return Value
If the elements being compared are of the same type, compare their values and return the result.
If the two elements are not of the same type, check whether they are numbers.
- If they are numbers, perform necessary numeric coercion, then compare.
- If one side's element is a number, then the other side's element is "greater" (numbers are "smallest").
- Otherwise, compare them by the alphabetical order of type names.
If one list reaches the end first, the other, longer list is "greater".
If we exhaust the elements of both lists and all elements are equal, then the result is a tie, that is, it returns 0.
Example
The following example demonstrates the usage of the cmp() function:
#!/usr/bin/python list1, list2 = [123, 'xyz'], [456, 'abc'] print cmp(list1, list2); print cmp(list2, list1); list3 = list2 + [786]; print cmp(list2, list3)
The output of the above example is as follows:
-1 1 -1Other Extensions
Python List