The symmetric_difference()
method returns all the items present in given sets, except the items in their intersections.
Example
A = {'a', 'b', 'c', 'd'}
B = {'c', 'd', 'e' }
# returns all items to result variable except the items on intersection
result = A.symmetric_difference(B)
print(result)
# Output: {'a', 'b', 'e'}
symmetric_difference() Syntax
The syntax of the symmetric_difference()
method is:
A.symmetric_difference(B)
Here, A and B are two sets.
symmetric_difference() Parameter
The symmetric_difference()
method takes a single parameter:
- B - a set that pairs with set A to find their symmetric difference
symmetric_difference() Return Value
The symmetric_difference()
method returns:
- a set with all the items of A and B excluding the excluding the identical items
Example 1: Python Set symmetric_difference()
A = {'Python', 'Java', 'Go'}
B = {'Python', 'JavaScript', 'C' }
# returns the symmetric difference of A and B to result variable
result = A.symmetric_difference(B)
print(result)
Output
{'Go', 'Java', 'C', 'JavaScript'}
In the above example, we have used symmetric_difference()
to return the symmetric difference of A and B to the result variable.
Here, 'Python'
is present in both sets A and B. So, the method returns all the items of A and B to result except 'Python'
.
Example 2: Python Set symmetric_difference()
A = {'a', 'b', 'c'}
B = {'a', 'b', 'c'}
# returns empty set
result = A.symmetric_difference(B)
print(result)
Output
set()
In the above example, we have used symmetric_difference()
with two sets A and B. Here, A and B are superset of each other, meaning all the items of A are present in B and vice versa.
In this case, the method returns an empty set.
Example 3: Symmetric Difference Using ^ Operator
We can also find the symmetric difference using the ^
operator in Python. For example,
A = {'a', 'b', 'c', 'd'}
B = {'c', 'd', 'e' }
C = {'i'}
# works as (A).symmetric_difference(B)
print(A ^ B)
# symmetric difference of 3 sets
print(A ^ B ^ C)
Output
{'a', 'b', 'e'} {'b', 'a', 'i', 'e'}
In the above example, we have used the ^
operator to find the symmetric difference of A and B and A, B and C. With ^
operator, we can also find the symmetric difference of 3 sets.
Also Read: