Python program to check if two sets are equal:
Python set is an inbuilt data type and it is used to store collection of data. set doesn’t allow any duplicate elements and its items are unordered and unindex.
This post will show you how to check if two sets are equal or not. We will learn two different ways to do that.
Method 1: By using == operator:
We can check if two sets are equal or not by using the == operator. It will check if two sets are equal or not and return one boolean value.
For example:
first_set = {'one', 'two', 'three'}
second_set = {'one', 'two', 'three'}
print(first_set == second_set)
It will print:
True
But for the below example:
first_set = {'one', 'two', 'three'}
second_set = {'one', 'two', 'three', 'four'}
print(first_set == second_set)
It will print:
False
For:
first_set = {'one', 'two', 'three', 'one'}
second_set = {'one', 'two', 'three'}
print(first_set == second_set)
It will print True because we can’t have duplicate items in a set.
Method 2: By using symmetric_difference:
We can also use symmetric_difference to find the difference between two set contents. summetric_difference will return one set with zero elements if both contains similar elements. We can check the length of the returned set to find if both are equal or not.
Below is the complete program:
first_set = {'one', 'two', 'three'}
second_set = {'one', 'two', 'three', 'one'}
if len(first_set.symmetric_difference(second_set)) == 0:
print('Both sets are equal')
else:
print('Sets are not equal')
If you run this program, it will print the below output:
Both sets are equal
You might also like:
- Python program to check if a subarray is in an array
- How to calculate gross pay for hourly paid employees in Python
- Python program to find the volume of a tetrahedron
- Python program to search for a text in a file
- How to insert an item to the start of an Ordered dictionary in Python
- How to write a simple stopwatch in python