The symmetric_difference() function in python returns a new set that containing the symmetric difference of two sets. The symmetric difference means the set of elements are either in the first set or in the second set. It doesn't contain common elements in the set.
A.symmetric_difference(B) #where A & B are sets
The symmetric_difference() function takes sets as its parameter. Python has another option for finding the symmetric difference that is by using the ^ operator.
Parameter | Description | Required / Optional |
---|---|---|
A & B | The set to check for matches in | Required |
The return value is always a set containing a mix of elements except the common elements.
Input | Return Value |
---|---|
sets | a set with symmetric difference |
A = {1, 2, 3, 4}
B = {2, 5, 6 }
C = {7, 5}
print(A.symmetric_difference(B))
print(B.symmetric_difference(A))
print(A.symmetric_difference(C))
print(B.symmetric_difference(C))
Output:
{1, 3, 4, 5, 6} {5, 6, 4, 1, 3} {1, 3, 4, 5, 6, 7} {'2', '5', '7'}
X = {1, 2, 3, 4}
Y = {5, 3, 1}
print(X ^ Y)
print(Y ^ X)
print(X ^ X)
print(Y ^ Y)
Output:
{2, 4, 5} {4, 2, 5} set() set()