Python Set difference() Method
The difference() method returns a new set containing elements that are in the first set but not in the any of the other specified sets.
Syntax
Using The difference() Method
set1.difference(set2, set3, ...)
Using the - Operator
set1 - set2 - set3
Parameters
set2, set3, ...: Other sets or iterables (such as lists or tuples) that you want to compare against.
Return Value
Returns a new set containing elements that appear only in the first set but not in any of the other specified sets or iterables.
Examples
Example 1: Difference between two sets
a = {1, 2, 3, 4}
b = {4, 5, 6, 7}
result = a.difference(b)
print(result) # Output: {1, 2, 3}
Example: Difference across multiple sets
You can pass mutliple sets, separated by commas, as arguments to the difference() method.
a = {1, 2, 3, 4}
b = {4, 5, 6, 7}
c = {3, 4, 8, 9}
result = a.difference(b, c)
print(result) # Output: {1, 2}
Example: Set difference with different iterable types
You can also pass iterables of different types (such as lists and tuples) as argument to the difference() method.
a = {1, 2, 3, 4}
b = [3, 5, 7, 9]
c = (4, 20, 15, 20)
result = a.difference(b, c)
print(result) # Output: {1, 2}
The - Operator
The - operator is a shorthand for performing a set difference.
a = {1, 2, 3, 4}
b = {4, 5, 6, 7}
c = {3, 4, 8, 9}
result = a - b - c
print(result) # Output: {1, 2}
Read Also: