Python difference between two sets | Example code

  • by

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

Simple example code gets the difference between two sets using difference() between set A and set B.

The set difference of 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:

Python difference between two sets

Or 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 (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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.