In Python, the set
data type is used to represent a collection of unique and unordered elements.Sets supports various operations, in this article, we will focus on how to get the difference of two sets.
If you have two sets A
and B
, the difference of the two(A - B
) is a set containing all the elements that are in A
but not in B
.
The difference()
method in sets is used to get the difference of two sets. It has the following syntax.
A.difference(B)
Where A
and B
are sets.
The function returns a new set containing the elements that are unique to set A
.
An alternative approach
We can also get the difference of two sets using the minus operator(-
). This way, we use the following syntax:
diff = A - B
Similarly, the operation returns the elements in set A
that are not in set B
.