Check if two sets are equal Python

While working with lists in Python, you might have encountered two lists which seem similar. To figure out the difference, you have to compare the data items of both lists. You can do this by using the set(), difference() and sort() methods.

In this article, we will understand how to compare two lists in Python.   

Comparing lists in Python 

There are different ways to compare lists in Python. But it depends on the outcome required. Two of the most popular methods are set() and cmp().

The set() function creates an object that is a set object. The cmp() function is used to compare two elements or lists and return a value based on the arguments passed.

In the following sections, we will see the application of  set(), cmp(), and difference() functions.

What is set() Function in Python?

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

Example of set() Function

1) Initializing List and Convert into Set Object

# initializing list    and convert into set object n = set(['n1','n4','n3','n2']) #Add new Element in set n n.add('n5'); print("Output with set Function : ") print(n)

Output:

Output with set Function : {'n5', 'n4', 'n1', 'n2', 'n3'}

At first, we convert a list into the set by using a set() function, now we need to check if both the lists are equal or not by using if operator.

# Python 3 code  # check if list are equal  # using set() # initializing list and convert into set object x = set(['x1','rr','x3','e4']) y = set(['x1','rr','e4','x3']) print ("List first: " + str(x)) print ("List second: " + str(y)) # check if list x equals to y if x == y:     print("First and Second list are Equal") else:     print("First and Second list are Not Equal")

Output:

List first: {'x3', 'x1', 'rr', 'e4'} List second: {'x3', 'x1', 'rr', 'e4'} First and Second list is Equal

Example Using Set() & Difference() Functions

In the following example, we first convert a list into the set by using set() function then we need to differentiate between these two sets by using difference() function and use the if() condition to check the return value.

# Python 3 code  # check if list are equal  # using set() & difference() # initializing list and convert into set object x = set(['x1','rr','x3','y4']) y = set(['x1','rr','rr','y4']) print ("List first: " + str(x)) print ("List second: " + str(y)) # take difference of two lists z = x.difference(y) print("Difference of first and second String: " + str(z)) # if lists are equal if not z:     print("First and Second list are Equal") # if lists are not equal     else:     print("First and Second list are Not Equal")

Output:

List first: {'y4', 'x3', 'rr', 'x1'} List second: {'y4', 'rr', 'x1'} Difference of first and second String: {'x3'} First and Second list are Not Equal

In this example, we first sort the list, so that element of the list is in the same order and then compare both the list with == operator

# Python 3 code  # check if list are equal  # using sort() & == operator # initializing list and convert into set object x = ['x1','rr','x3','y4'] y = ['x1','rr','rr','y4'] print ("List first: " + str(x)) print ("List second: " + str(y)) # sort list x and y x.sort() y.sort() # if lists are equal if x == y:     print("First and Second list are Equal") # if lists are not equal     else:     print("First and Second list are Not Equal")

Output:

List first: ['x1', 'rr', 'x3', 'y4'] List second: ['x1', 'rr', 'rr', 'y4'] First and Second list are Not Equal

Comparing two lists in Python using a Custom Function

In this example, we need to check the elements one by one whether it's available in List 1 or List2.

# Custom python code to check if list one is equal to list two by taking difference # Define function name difference 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     # Initializing list 1 and list 2 x = [10, 15, 20, 25, 30, 35, 40] y = [25, 40, 35] print ("List first: " + str(x)) print ("List second: " + str(y)) # Take difference of list 1 and list 2 z = difference (x, y) print("Difference of first and second String: " + str(z)) # if lists are equal if not z:     print("First and Second list are Equal") # if lsts are not equal     else:     print("First and Second list are Not Equal")

Output: 

List first: [10, 15, 20, 25, 30, 35, 40] List second: [25, 40, 35] Difference of first and second String: [10, 15, 20, 30] First and Second list are Not Equal

The cmp() function is a built-in method in Python used to compare 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.

Note: cmp() build to function for python version 2, In python version 3 it is not available.

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

If a>b, then value 1 is returned  If a<b, value -1 is returned 

If a=b, value 0 is returned 

Compared Two Lists Using Cmp() Function

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))

Output

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

Apart from the methods discussed above, you can use collection.Counter(), reduce(), map() and using sum(), zip() and len() methods together; to compare two lists in Python.  

While programming in python, comparison has to be done very often for checking different conditions. We may need to compare two variables or two groups of variables for a single condition checking. In this article we will try different ways to compare two lists in python. While comparing, we will have to check if both the lists contain the same elements or not irrespective of the order in which the elements are present in the lists. Accordingly, we will have to print the result.

Compare two lists using sort() method

To check whether two lists contain the same elements or not, we can use  the sort() method to sort the elements of the lists first. Then, we can compare the two lists.

For comparison,first we will check if the length of the lists are equal or not. If the lengths are not equal, the lists will be automatically considered as different. 

Check if two sets are equal Python

If the length of the lists are the same, we will sort the two lists. Then we will compare the lists using the == operator to check whether the lists are equal or not. If the sorted lists are equal, it will establish that both the original lists contain the same elements. This can be implemented as follows.

# function to compare lists def compare(l1, l2): # here l1 and l2 must be lists if len(l1) != len(l2): return False l1.sort() l2.sort() if l1 == l2: return True else: return False list1 = [1, 2, 3, 4] list2 = [1, 4, 3, 2] list3 = [2, 3, 4, 5] print("list1 is:",list1) print("list2 is:",list2) print("list3 is:",list3) # comparing list1 and list 2 print("list1 and list2 contain same elements:",compare(list1, list2)) #comparing list2 and list3 print("list1 and list3 contain same elements:",compare(list1, list3))

Output:

list1 is: [1, 2, 3, 4] list2 is: [1, 4, 3, 2] list3 is: [2, 3, 4, 5] list1 and list2 contain same elements: True list1 and list3 contain same elements: False

Compare using sets in Python

To compare two lists in python, we can use sets. A set in python only allows unique values in it. We can use this property of sets to find if two lists have the same elements or not.

For comparison,first we will check if the length of the lists are equal or not. If the lengths are not equal, the lists will be automatically flagged as different.

After that, we will convert the lists into sets using set() constructor. We can compare the two sets using the == operator to check if both the sets are equal or not. If both sets are equal, it will be established that both the lists contain equal values. Following example illustrates this concept.

# function to compare lists def compare(l1, l2): # here l1 and l2 must be lists if len(l1) != len(l2): return False set1 = set(l1) set2 = set(l2) if set1 == set2: return True else: return False list1 = [1, 2, 3, 4] list2 = [1, 4, 3, 2] list3 = [2, 3, 4, 5] print("list1 is:", list1) print("list2 is:", list2) print("list3 is:", list3) # comparing list1 and list 2 print("list1 and list2 contain same elements:", compare(list1, list2)) # comparing list2 and list3 print("list1 and list3 contain same elements:", compare(list1, list3))

Output:

list1 is: [1, 2, 3, 4] list2 is: [1, 4, 3, 2] list3 is: [2, 3, 4, 5] list1 and list2 contain same elements: True list1 and list3 contain same elements: False

Compare two lists using frequency counter

We can also compare two lists without comparing their lengths. For this, first we will have to create a python dictionary for each list which will keep track of the frequency of the elements in the lists. After creating the dictionaries where elements of the lists are stored as keys and their frequency are stored as values, we can compare the frequency of each element in the two dictionaries. If the frequency of each elements becomes equal, it will be confirmed that both the lists contained equal elements.

For this task, we can use the counter() method. The counter() method, when invoked on a list, creates a python dictionary and stores the elements as keys and their frequency as values in it. After invoking the counter() method, we can compare the created dictionary using == operator to check whether the frequency of every element is equal or not. If the result is True, the lists contain equal elements. Otherwise not. This can be seen from the following example.

import collections # function to compare lists def compare(l1, l2): # here l1 and l2 must be lists if len(l1) != len(l2): return False counter1 = collections.Counter(l1) counter2=collections.Counter(l2) if counter1 == counter2: return True else: return False list1 = [1, 2, 3, 4] list2 = [1, 4, 3, 2] list3 = [2, 3, 4, 5] print("list1 is:", list1) print("list2 is:", list2) print("list3 is:", list3) # comparing list1 and list 2 print("list1 and list2 contain same elements:", compare(list1, list2)) # comparing list2 and list3 print("list1 and list3 contain same elements:", compare(list1, list3))

Output:

list1 is: [1, 2, 3, 4] list2 is: [1, 4, 3, 2] list3 is: [2, 3, 4, 5] list1 and list2 contain same elements: True list1 and list3 contain same elements: False

Conclusion

In this article, we have seen three different ways to compare two lists in python and have checked if they contain the same elements without considering the position of the elements. To read more about lists, read this article on list comprehension.

In the compare() function used in the examples, it may be possible that user passes two other objects instead of lists. In such cases, the program may run into error. To avoid this, we can use exception handling using python try except to avoid runtime errors by applying type checking using type() method in try-except block to check if the objects passed as arguments are lists.

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.