Python Set symmetric_difference() Method
The symmetric_difference() method returns a new set containing elements that are in either of the sets, but not in both.
Syntax
set1.symmetric_difference(set2)
Using the ^ Operator
set1 ^ set2
Parameters
set2: Another set (or any iterable) to compare with.
Return Value
Returns a new set containing elements that are unique to each of the sets.
Examples
Example 1: Symmetric difference of two sets
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1.symmetric_difference(set2)
print(result) # Output: {1, 2, 5, 6}
Example 2: Symmetric difference with other iterable types
You can also pass an iterable of a different type (such as a list or tuple) as the single argument to the symmetric_difference() method.
set1 = {1, 2, 3, 4}
list1 = [3, 4, 5, 6] # a list
tuple1 = (1, 2, 9, 10) # a tuple
# Symmetric difference between a set and a list
result1 = set1.symmetric_difference(list1)
print(result1) # Output: {1, 2, 5, 6}
# Symmetric difference between a set an a tuple
result2 = set1.symmetric_difference(tuple1)
print(result2) # Output: {3, 4, 9, 10}
Using The ^ Operator
The ^ operator is a shorthand for performing a symmetric difference.
For example:
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result = set1 ^ set2
print(result) # Output: {1, 2, 5, 6}
Also Read:
Python Set symmetric_difference_update() Method