Use symmetric_difference() method to get the symmetric difference set in Python. This method returns a new set that contains all items from both sets, but not the items that are present in both sets
set.symmetric_difference(set)
Python Example get the Set symmetric difference
Simple example code gets the elements that are not common in both sets.
set1 = {1, 2, 3, 4, 5}
set2 = {1, 2, 3, 6, 0}
new_set = set1.symmetric_difference(set2)
print(new_set)
Output:
Another example
Find the symmetric difference using the ^
operator.
set1 = {'A', 'B'}
set2 = {'A','C'}
new_set = set1 ^ set2
print(new_set)
Output: {‘C’, ‘B’}
The symmetric_difference() method vs symmetric difference operator (^)
The symmetric_difference() method accepts one or more iterables that can be strings, lists, or dictionaries. And the symmetric difference operator (^
) only applies to sets. If you use it with the iterables which aren’t sets, you’ll get an error.
set1 = {'A', 'B'}
set2 = ['A','C']
new_set = set1 ^ set2
print(new_set)
Output: TypeError: unsupported operand type(s) for ^: ‘set’ and ‘list’
Do comment if you have any doubts or suggestions on this Python set tutorial.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.