Use the difference() method to get the difference between two sets in Python. This method returns the difference between two sets which is also a set. It doesn’t modify the original sets.
A.difference(B)
Example difference between two sets in Python
A simple example code gets the difference between two sets using the difference() between sets A and B.
The set difference between A and B is a set of elements that exist only in set A but not in B. For example:
A = {'A', 'B', 'C', 'D'}
B = {'C', 'F', 'X'}
# Equivalent to A-B
print(A.difference(B))
# Equivalent to B-A
print(B.difference(A))
Output:
You can also find the set difference using -
operator in Python.
A = {'A', 'B', 'C', 'D'}
B = {'C', 'F', 'X'}
print(A - B)
print(B - A)
Output:
{‘D’, ‘A’, ‘B’}
{‘F’, ‘X’}
Do comment if you have any doubts or suggestions on this Python sets topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.