The set.difference() method in Python returns a new set containing elements that are present in the first set but not in the other given set(s). It performs set subtraction and removes all common elements. The original sets remain unchanged.

Example: In this example, elements that are present in one set but not in another are found using difference().
a = {10, 20, 30, 40, 80}
b = {100, 30, 80, 40, 60}
print(a.difference(b))
print(b.difference(a))
Output
{10, 20}
{100, 60}
Explanation:
- a.difference(b) returns elements in a not in b.
- b.difference(a) returns elements in b not in a.
Syntax
set1.difference(set2, set3, ...)
- Parameters: One or more sets whose elements need to be removed from the first set.
- Return Value: Returns a new set containing elements unique to the first set.
Examples
Example 1: In this example, the difference is calculated using multiple sets.
a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7}
c = {5, 6, 7, 8, 9}
print(a.difference(b, c))
Output
{1, 2}
Explanation: a.difference(b, c) removes elements found in b or c, only elements unique to a remain.
Example 2: Here, the difference of a set with an empty set is demonstrated.
a = {10, 20, 30, 40}
b = set()
print(a.difference(b))
Output
{40, 10, 20, 30}
Explanation: a.difference(b) removes elements of b from a. Since b is empty, a remains unchanged.
Example 3: In this example, the difference operation is performed when one set is a subset of another.
a = {10, 20, 30, 40, 80}
b = {10, 20, 30, 40, 80, 100}
print(a.difference(b))
Output
set()
Explanation:
- All elements of a exist in b.
- a.difference(b) returns an empty set.
- No unique elements remain in a.