Computer >> Computer tutorials >  >> Programming >> Python

How do we compare the elements of two lists in Python?


The method cmp() compares elements of two lists. If elements are of the same type, it performs the compare and returns the result. If elements are different types, it checks to see if they are numbers. If they are numbers, it performs type coercion if necessary and compares. If either element is a number, then the other element is "larger" (numbers are "smallest"). Otherwise, types are sorted alphabetically by name.

If we reached the end of one of the lists, the longer list is "larger." If we exhaust both lists and share the same data, the result is a tie, meaning that 0 is returned.

 example

list1 = [123, 'xyz']
list2 = [456, 'abc']
print(cmp(list1, list2))
print(cmp(list2, list1))
list2 = [123, 'xyz']
print(cmp(list1, list2))

Output

This will give the output −

-1
1
0