The difference()
method is used to get the set of elements that are present in one set but not in another. It returns a new set that contains all the elements from the original set that are not present in the specified set(s).
difference()
method:
set1.difference(set2, set3, ...)
set1
: The original set from which you want to get the difference.set2
, set3
, ...: The sets you want to compare with set1
.Note that you can provide multiple sets as arguments to the difference()
method to compare them with the original set.
# Creating two sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
# Getting the difference between set1 and set2
result_set = set1.difference(set2)
print(result_set) # Output: {1, 2, 3} (elements that are present in set1 but not in set2)
In this example, the difference()
method is applied to set1
, and it takes set2
as an argument. The result is a new set containing elements that are present in set1
(1, 2, 3) but not present in set2
(6, 7, 8).
You can also provide multiple sets to the difference()
method:
# Creating three sets
set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
set3 = {3, 4, 6}
# Getting the difference between set1 and set2, set3
result_set = set1.difference(set2, set3)
print(result_set) # Output: {1, 2} (elements that are present in set1 but not in set2 or set3)
In this case, the difference()
method is used with both set2
and set3
as arguments, and the result is a set containing elements that are present in set1
(1, 2) but not present in either set2
or set3
.