Set Operations
Set objects also support mathematical operations like union, intersection, difference, and symmetric difference.
Union
Union of two sets is a set containing all elements of both sets.
set_a | set_b
or
set_a.union(sequence)
union()
converts sequence to a set, and performs the union. Code
PYTHON
Output
Code
PYTHON
Output
Intersection
Intersection of two sets is a set containing common elements of both sets.
set_a & set_b
or
set_a.intersection(sequence)
intersection()
converts sequence to a set, and perform the intersection. Code
PYTHON
Output
Code
PYTHON
Output
Difference
Difference of two sets is a set containing all the elements in the first set but not second.
set_a - set_b
or
set_a.difference(sequence)
difference()
converts sequence to a set.Code
PYTHON
Output
Code
PYTHON
Output
Symmetric Difference
Symmetric difference of two sets is a set containing all elements which are not common to both sets.
set_a ^ set_b
or
set_a.symmetric_difference(sequence)
symmetric_difference()
converts sequence to a set.Code
PYTHON
Output
Code
PYTHON
Output
Set Comparisons
Set comparisons are used to validate whether one set fully exists within another
- issubset()
- issuperset()
- isdisjoint()
Subset
set2.issubset(set1)
Returns True
if all elements of second set are in first set. Else, False
Example - 1
Code
PYTHON
Output
Example - 2
Code
PYTHON
Output
SuperSet
set1.issuperset(set2)
Returns True
if all elements of second set are in first set. Else, False
Example - 1
Code
PYTHON
Output
Example - 2
Code
PYTHON
Output
Disjoint Sets
set1.isdisjoint(set2)
Returns True
when they have no common elements. Else, False
Code
PYTHON