In Python, we can find the symmetric difference of two sets easily with the set symmetric_difference() function.
a = {0, 1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
print(a.symmetric_difference(b))
#Output:
{0, 1, 2, 6, 7, 8}
You can also get the symmetric difference of two sets with the ^ operator.
a = {0, 1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
print(a^ b)
#Output:
{0, 1, 2, 6, 7, 8}
In Python, sets are unordered collections of items. When working with sets, it can be useful to know all of the elements which are only in one set, but not the other set.
The symmetric difference of two sets is the set of elements that are in either of the sets, but not in the intersection of the sets.
We can easily find the symmetric difference of two sets in Python with the set symmetric_difference() function.
Below is a simple Python example of how to find the symmetric difference of two sets.
a = {0, 1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
print(a.symmetric_difference(b))
#Output:
{0, 1, 2, 6, 7, 8}
Symmetric Difference of Two Lists in Python
If you are working with lists and need to find the symmetric difference of two lists, you can easily do so by converting the lists to sets.
To convert a list to a set, use set(). Then we can call the symmetric_difference() function on the new set and pass the other converted list.
Below is an example of how to get the symmetric difference of two lists in Python.
a = [0, 1, 2, 3, 4, 5]
b = [3, 4, 5, 6, 7, 8]
print(set(a).symmetric_difference(set(b)))
#Output:
{0, 1, 2, 6, 7, 8}
Symmetric Difference of Two Sets with ^ Operator in Python
You can also get the symmetric difference of two sets with the ^ operator. The ^ operator gets all elements which are in the first set but not in the second set, and in the second set but not in the first set.
Below is how to get the symmetric difference of two sets using the ^ operator in Python.
a = {0, 1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7, 8}
print(a^ b)
#Output:
{0, 1, 2, 6, 7, 8}
Hopefully this article has been useful for you to learn how to find the symmetric difference of sets in Python.