Open In App

Python Set difference()

Last Updated : 26 Feb, 2025
Summarize
Comments
Improve
Suggest changes
Share
Like Article
Like
Report

In Python, the difference() method is used to find elements that exist in one set but not in another. It returns a new set containing elements from the first set that are not present in the second set. This operation is similar to the subtraction of sets (A - B), where only unique elements from the first set remain. For example:

Python
A = {10, 20, 30, 40, 80}
B = {100, 30, 80, 40, 60}

print(A.difference(B))  # Elements in A but not in B
print(B.difference(A))  # Elements in B but not in A

Output
{10, 20}
{100, 60}

Let’s look at the Venn diagram of the following difference set function.

set-differenceSyntax:

set_A.difference(set_B) for (A - B)
set_B.difference(set_A) for (B - A)

Using difference() with Multiple Sets

difference() method can be used with multiple sets to find elements unique to the first set compared to all others.

Python
A = {1, 2, 3, 4, 5}
B = {3, 4, 5, 6, 7}
C = {5, 6, 7, 8, 9}

res = A.difference(B, C)  # Elements in A that are not in B or C
print(res)

Output
{1, 2}

Explanation: elements {3, 4, 5} are common in A and at least one of B or C, so they are removed from A. The remaining elements {1, 2} are unique to A thereby forming the result.

Using difference() with an Empty Set

If we take the difference of a set with an empty set then the original set remains unchanged.

Python
A = {10, 20, 30, 40}
B = set()

print(A.difference(B))

Output
{40, 10, 20, 30}

Explanation: Since B is empty there are no elements to remove from A hence the result remains the same as A.

When Sets Are Equal

If two sets are equal or one is a subset of the other, the difference results in an empty set.

Python
A = {10, 20, 30, 40, 80}
B = {10, 20, 30, 40, 80, 100}

print(A.difference(B))  # Returns an empty set as A is fully contained in B

Output
set()

Explanation: Since all elements of A are present in B, there are no unique elements left in A after performing the difference operation hence resulting in an empty set.


Next Article
Article Tags :
Practice Tags :

Similar Reads