Python Set Operations
Set can be performed mathematical operation such as union, intersection, difference, and symmetric difference. Python provides the facility to carry out these operations with operators or methods. We describe these operations as follows.
Union of two Sets
The union of two sets is calculated by using the pipe (|) operator. The union of the two sets contains all the items that are present in both the sets.
Consider the following example to calculate the union of two sets.
Example 1: using union | operator
Days1 = {"Monday","Tuesday","Wednesday","Thursday", "Sunday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1|Days2) #printing the union of the sets
Output:
{'Friday', 'Sunday', 'Saturday', 'Tuesday', 'Wednesday', 'Monday', 'Thursday'}
Python also provides the union() method which can also be used to calculate the union of two sets. Consider the following example.
Example 2: using union() method
Days1 = {"Monday","Tuesday","Wednesday","Thursday"}
Days2 = {"Friday","Saturday","Sunday"}
print(Days1.union(Days2)) #printing the union of the sets
Output:
{'Friday', 'Monday', 'Tuesday', 'Thursday', 'Wednesday', 'Sunday', 'Saturday'}
Intersection of two sets
The intersection of two sets can be performed by the and & operator or the intersection() function . The intersection of the two sets is given as the set of the elements that common in both sets.
Consider the following example.
Example 1: Using & operator
Days1 = {"Monday","Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday","Tuesday","Sunday", "Friday"}
print(Days1&Days2) #prints the intersection of the two sets
Output:
{'Monday', 'Tuesday'}
Example 2: Using intersection() method
set1 = {"Devansh","John", "David", "Martin"}
set2 = {"Steve", "Milan", "David", "Martin"}
print(set1.intersection(set2)) #prints the intersection of the two sets
Output:
{'Martin', 'David'}
Example 3:
set1 = {1,2,3,4,5,6,7}
set2 = {1,2,20,32,5,9}
set3 = set1.intersection(set2)
print(set3)
Output:
{1,2,5}
The intersection_update() method
The intersection_update() method removes the items from the original set that are not present in both the sets (all the sets if more than one are specified).
The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items, on the other hand, the intersection() method returns a new set.
Consider the following example.
a = {"Devansh", "bob", "castle"}
b = {"castle", "dude", "emyway"}
c = {"fuson", "gaurav", "castle"}
a.intersection_update(b, c)
print(a)
Output:
{'castle'}
Difference between the two sets
The difference of two sets can be calculated by using the subtraction (-) operator or intersection() method. Suppose there are two sets A and B, and the difference is A-B that denotes the resulting set will be obtained that element of A, which is not present in the set B.
Consider the following example.
Example 1 : Using subtraction ( - ) operator
Days1 = {“Monday”, “Tuesday”, “Wednesday”, “Thursday”}
Days2 = {“Monday”, “Tuesday”, “Sunday”}
print(Days1-Days2) #{“Wednesday”, “Thursday” will be printed}
Output:
{'Thursday', 'Wednesday'}
Example 2 : Using difference() method
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday", "Sunday"}
print(Days1.difference(Days2)) # prints the difference of the two sets Days1 and Days2
Output:
{'Thursday', 'Wednesday'}
Symmetric Difference of two sets
The symmetric difference of two sets is calculated by ^ operator or symmetric_difference() method. Symmetric difference of sets, it removes that element which is present in both sets. Consider the following example:
Example - 1: Using ^ operator
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a^b
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Example - 2: Using symmetric_difference() method
a = {1,2,3,4,5,6}
b = {1,2,9,8,10}
c = a.symmetric_difference(b)
print(c)
Output:
{3, 4, 5, 6, 8, 9, 10}
Set comparisons
Python allows us to use the comparison operators i.e., <, >, <=, >= , == with the sets by using which we can check whether a set is a subset, superset, or equivalent to other set. The boolean true or false is returned depending upon the items present inside the sets.
Consider the following example.
Days1 = {"Monday", "Tuesday", "Wednesday", "Thursday"}
Days2 = {"Monday", "Tuesday"}
Days3 = {"Monday", "Tuesday", "Friday"}
#Days1 is the superset of Days2 hence it will print true.
print (Days1>Days2)
#prints false since Days1 is not the subset of Days2
print (Days1<Days2)
#prints false since Days2 and Days3 are not equivalent
print (Days2 == Days3)
Output:
True
False
False
FrozenSets
FrozenSets
The frozen sets are the immutable form of the normal sets, i.e., the items of the frozen set cannot be changed and therefore it can be used as a key in the dictionary.
The elements of the frozen set cannot be changed after the creation. We cannot change or append the content of the frozen sets by using the methods like add() or remove().
The frozenset() method is used to create the frozenset object. The iterable sequence is passed into this method which is converted into the frozen set as a return type of the method.
Consider the following example to create the frozen set.
Frozenset = frozenset([1,2,3,4,5])
print(type(Frozenset))
print("\nprinting the content of frozen set...")
for i in Frozenset:
print(i);
Frozenset.add(6) #gives an error since we cannot change the content of Frozenset after creation
Output:
<class 'frozenset'>
printing the content of frozen set...
1
2
3
4
5
Traceback (most recent call last):
File "set.py", line 6, in <module>
Frozenset.add(6) #gives an error since we can change the content of Frozenset after creation
AttributeError: 'frozenset' object has no attribute 'add'
Frozenset for the dictionary
If we pass the dictionary as the sequence inside the frozenset() method, it will take only the keys from the dictionary and returns a frozenset that contains the key of the dictionary as its elements.
Consider the following example.
Dictionary = {"Name":"John", "Country":"USA", "ID":101}
print(type(Dictionary))
Frozenset = frozenset(Dictionary); #Frozenset will contain the keys of the dictionary
print(type(Frozenset))
for i in Frozenset:
print(i)
Output:
<class 'dict'>
<class 'frozenset'>
Name
Country
ID
Set Programming Example
Example - 1: Write a program to remove the given number from the set.
my_set = {1,2,3,4,5,6,12,24}
n = int(input("Enter the number you want to remove"))
my_set.discard(n)
print("After Removing:",my_set)
Output:
Enter the number you want to remove:12
After Removing: {1, 2, 3, 4, 5, 6, 24}
Example - 2: Write a program to add multiple elements to the set.
set1 = set([1,2,4,"John","CS"])
set1.update(["Apple","Mango","Grapes"])
print(set1)
Output:
{1, 2, 4, 'Apple', 'John', 'CS', 'Mango', 'Grapes'}
Example - 3: Write a program to find the union between two set.
set1 = set(["Peter","Joseph", 65,59,96])
set2 = set(["Peter",1,2,"Joseph"])
set3 = set1.union(set2)
print(set3)
Output:
{96, 65, 2, 'Joseph', 1, 'Peter', 59}
Example- 4: Write a program to find the intersection between two sets.
set1 = {23,44,56,67,90,45,"Javatpoint"}
set2 = {13,23,56,76,"Sachin"}
set3 = set1.intersection(set2)
print(set3)
Output:
{56, 23}
Example - 5: Write the program to add element to the frozenset.
set1 = {23,44,56,67,90,45,"Javatpoint"}
set2 = {13,23,56,76,"Sachin"}
set3 = set1.intersection(set2)
print(set3)
Output:
TypeError: 'frozenset' object does not support item assignment
Above code raised an error because frozensets are immutable and can’t be changed after creation.
Example - 6: Write the program to find the issuperset, issubset and superset.
set1 = set(["Peter","James","Camroon","Ricky","Donald"])
set2 = set(["Camroon","Washington","Peter"])
set3 = set(["Peter"])
issubset = set1 >= set2
print(issubset)
issuperset = set1 <= set2
print(issuperset)
issubset = set3 <= set2
print(issubset)
issuperset = set2 >= set3
print(issuperset)
Output:
False
False
True
True