Python Set symmetric_difference() Method
The symmetric_difference() method can be used to find the symmetric difference of two sets.
The symmetric_difference() method returns a set of non-duplicate elements from the two sets, that is, it removes elements that exist in both sets.
Syntax
The syntax of the symmetric_difference() method is:
set.symmetric_difference(set)
Parameters
- set -- Set
Return Value
Returns a new set.
Example
Return a new set composed of the two sets, but remove duplicate elements from both sets:
Example 1
x = {"apple", "banana", "cherry"}
y = {"google", "example", "apple"}
z = x.symmetric_difference(y)
print(z)
The output result is:
{'google', 'cherry', 'banana', 'example'}
You can also use the^operator to achieve the same effect:
Example
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 ^ set2
print(result) # Output: {1, 2, 5, 6}
set2 = {3, 4, 5, 6}
result = set1 ^ set2
print(result) # Output: {1, 2, 5, 6}
The output result is:
{1, 2, 5, 6}
Python Sets