Last Updated : 26 Feb, 2025
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
{10, 20} {100, 60}
Let’s look at the Venn diagram of the following difference set function.
Syntax:Using difference() with Multiple Setsset_A.difference(set_B) for (A - B)
set_B.difference(set_A) for (B - A)
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)
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 SetIf 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))
Explanation: Since B is empty there are no elements to remove from A hence the result remains the same as A.
When Sets Are EqualIf 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
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4