Online Tutorials & Training Materials |
Register Login

Compare Lists in Python using Set() and Cmp() Function

|| 0

Compare Lists in Python using Set() and Cmp() Function

Lists in Python can be performed in different ways but it depends on the outcome required. Two very common methods of comparison are set() and cmp(). The set() function creates an object that is a set. The cmp() function is used to compare two elements or lists and return a value based on the arguments passed. 

What is Set() Function? 

The set() function in Python is used to take an argument and a convert it into a set object. It can take arguments like lists, tuples and dictionaries. The argument is called iterable. The resultant set might not have the same order of elements if the items passed as list were unordered. 

Two lists can be compared using the set() function by first passing them as arguments. After they get converted into sets, operations such as subtraction are used to compare each element. 

def Difference (list1, list2):
   list_dif = [i for i in list1 + list2 if i not in list1 or i not in list2]
   return list_dif
#Driver Code
list1 = [10, 15, 20, 25, 30, 35, 40]
list2 = [25, 40, 35]
      list3 = Difference (list1, list2)
      print (list3)

What is Cmp() Function? 

The cmp() function is a built-in method in Python that is used to compares the elements of two lists. The function is also used to compare two elements and return a value based on the arguments passed. This value can be 1, 0 or -1. 

For example, if a and b are two lists, then: 

If a>b, then 1 is returned 
If a<b, -1 is returned 
If a=b, 0 is returned 

Below is an example of two lists being compared using the cmp() function. 

#use of cmp() method
#where a=b, a<b and a>b these three comparison.
#when a<b
a = 1
b = 2
print(cmp(a, b))
#when a = b
a = 2
b = 2
print(cmp(a, b))
#when a>b
a = 3
b = 2
print(cmp(a, b))


a<b is true and results is -1.
where a=b are equal it returns 0.
where a>b  is the output is 1.