The difference()
function in Python set methods returns a new set containing elements that are present in the set but not in the specified iterable. It computes the difference between two sets and returns the result as a new set.
Parameter Values
Parameter | Description |
---|---|
other | A |
Return Values
The difference()
method returns a new set with elements not in the others.
How to Use difference()
in Python
Example 1:
The difference()
method returns a set that contains the difference between two sets. It gets the elements that are only in the first set and not in the second set.
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result = set1.difference(set2)
print(result) # Output: {1, 2}
Example 2:
The difference()
method can also be applied using the '-' operator between two sets.
set1 = {5, 6, 7}
set2 = {7, 8, 9}
result = set1 - set2
print(result) # Output: {5, 6}
Example 3:
If there are no elements different between the two sets, the difference()
method will return an empty set.
set1 = {10, 11, 12}
set2 = {10, 11, 12}
result = set1.difference(set2)
print(result) # Output: set()