Mathematical set operations in Python
The mathematical set operations can be applied to data items in Python to perform specific functions. The operators in Python for mathematical set operations are represented by special characters and keywords for different operations.
By applying mathematical set operations on sets, it is possible to compare the elements of multiple sets and even create new sets for comparisons. This article discusses mathematical set operations like Union, Intersection, Null intersection, and Intersection update operation in Python.
Mathematical set operation Union
The union of two sets is a standard mathematical set operation to merge the elements of two sets into a single set. In sets, union operation can be applied to more than 2 sets with the syntax set1.union(set2)
or set1|set2|set3
.

a = {'SPSS','Python','R','Tableau','MS Excel','MS Word','SQL'}
b = {'PHP','Java','CSS','Git','HTML','MS Excel','MS Word','SQL'}
c = {'MatLab', 'Meta Analysis', 'Critical Review', 'SAS'}
print(a|b|c)
#OUTPUT {'SQL', 'PHP', 'Meta Analysis', 'MS Word', 'MatLab', 'HTML', 'SAS', 'R', 'SPSS', 'Python', 'Git', 'CSS', 'Critical Review', 'Tableau', 'MS Excel', 'Java'}
print(a.union(b).union(c))
#OUTPUT {'SQL', 'PHP', 'Meta Analysis', 'MS Word', 'MatLab', 'HTML', 'SAS', 'R', 'SPSS', 'Python', 'Git', 'CSS', 'Critical Review', 'Tableau', 'MS Excel', 'Java'}
Mathematical set operation intersection in Python

The intersection of sets is the conjunction of sets at the common elements of the sets. The intersection of sets helps to identify the common elements in a group of sets.
a = {'SPSS','Python','R','Tableau','MS Excel','MS Word','SQL'}
b = {'PHP','Java','CSS','Git','HTML','MS Excel','MS Word','SQL'}
print(a & b)
#OUTPUT {'MS Word', 'MS Excel', 'SQL'}
Along with the &
operator, the intersection of sets can also be performed using the syntax set1.intersection(set2)
.
The null intersection of sets in Python
The null intersection of sets is a conditional method to check if the sets are truly disjoint. The syntax for the method is set1.isdisjoint(set2)
and it returns boolean values True
or False
.
a = {'SPSS','Python','R','Tableau','MS Excel','MS Word','SQL'}
b = {'PHP','Java','CSS','Git','HTML','MS Excel','MS Word','SQL'}
c = {'MatLab', 'Meta Analysis', 'Critical Review', 'SAS'}
print(a.isdisjoint(b))
#OUTPUT False
print(a.isdisjoint(c))
#OUTPUT True
Intersection Update of sets in Python
The intersection update method finds the intersecting elements in the group of sets and updates the first set with the output. In simpler terms, if set A is intersection updated with B, Set A will be updated with the intersecting elements of both A & B set.
a = {'SPSS','Python','R','Tableau','MS Excel','MS Word','SQL'}
b = {'PHP','Java','CSS','Git','HTML','MS Excel','MS Word','SQL'}
a.intersection_update(b)
print(a)
#OUTPUT {'MS Word', 'MS Excel', 'SQL'}
print(b)
#OUTPUT {'PHP', 'SQL', 'MS Word', 'HTML', 'Git', 'CSS', 'MS Excel', 'Java'}
Discuss