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
.
#define set A and B
A = {1, 2, 3, 4, 5, 6, 7, 8, 9}
B = {1, 3, 5, 7, 9}
#get the difference
diff = A.difference(B)
print(diff)
A = {'a', 'b', 'c', 'd', 'e', 'f'}
B = {'b', 'c', 'd'}
#get the difference
diff = A.difference(B)
print(diff)
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
.
#Define the sets
A = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
B = {2, 3, 5, 7}
#get the difference using the - operator
diff = A - B
print(diff)