Python set Method - symmetric_difference()

ww‮figi.w‬tidea.com

The symmetric_difference() method in Python sets returns a new set that contains all the elements that are in either of the two sets, but not in both. In other words, it returns the set of all elements that are in exactly one of the sets.

The syntax for the symmetric_difference() method is as follows:

set1.symmetric_difference(set2)

Here, set1 and set2 are the two sets for which we want to find the symmetric difference.

Example:

# Creating two sets
set1 = {1, 2, 3}
set2 = {2, 3, 4}

# Finding the symmetric difference between set1 and set2
result_set = set1.symmetric_difference(set2)

print(result_set)   # Output: {1, 4}

In the above example, the symmetric_difference() method is used to find the symmetric difference between set1 and set2. Since set1 contains the elements 1, 2, and 3, and set2 contains the elements 2, 3, and 4, the symmetric difference between the two sets is the set of all elements that are in exactly one of the sets, which is {1, 4}. The result set is printed using the print() function.