Python set Method - difference()
The difference()
method in Python is used to find the difference between two sets. The method returns a new set that contains elements that are in the first set but not in the second set.
The syntax for the difference()
method is as follows:
set_difference = set1.difference(set2)
Here, set1
and set2
are the two sets for which we need to find the difference. The method returns a new set set_difference
that contains elements that are in set1
but not in set2
.
Example:
# Creating two sets set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} # Finding the difference between the sets set_difference = set1.difference(set2) # Displaying the sets and the difference print(set1) # Output: {1, 2, 3, 4} print(set2) # Output: {3, 4, 5, 6} print(set_difference) # Output: {1, 2}
In the above example, the difference()
method is used to find the difference between the sets set1
and set2
. The new set set_difference
contains the elements that are in set1
but not in set2
. The original sets and the difference set are printed to show their contents. It is important to note that the order of elements in a set is undefined and may not match the order in which they were added. Also, the difference()
method does not modify the original sets, it only returns a new set that contains the difference.