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.

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.

ExampleEdit & Run
#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)
Output:
{8, 2, 4, 6}[Finished in 0.0111022989731282s]
ExampleEdit & Run
A = {'a', 'b', 'c', 'd', 'e', 'f'}
B = {'b', 'c', 'd'}

#get the difference
diff = A.difference(B)
print(diff)
Output:
{'f', 'a', 'e'}[Finished in 0.0096723937895149s]

An alternative approach

We can also get the difference of two sets using the minus operator(-). This way, we use the following syntax:

Syntax:
diff = A - B

 Similarly, the operation returns the elements in set A that are not in set B.

ExampleEdit & Run
#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)
Output:
{0, 1, 4, 6, 8, 9}[Finished in 0.01011214405298233s]