The symmetric_difference()
method in Python for two elements A and B is used to return the set of elements contained in both A and B but not common in both of them. In other words, it is used to produce the symmetric difference between two sets.
A.symmetric_difference(B)
Parameter | Description |
| This is the required argument. It is one of the sets we want to find its symmetric difference with a second set. |
| This is the required argument. It is one of the sets we want to find its symmetric difference with a second set. |
The symmetric_difference()
method returns a set of elements that represent the symmetrical difference between the two sets.
Let us create two sets, A and B, and then use the symmetric_difference()
method to obtain the symmetric difference between both sets as follows:
A = {'a','b','c','d'}B = {'a','f','g'}symmetry = A.symmetric_difference(B)print('The symmetry between A and B is=', symmetry)
Line 1: we defined set A
Line 2: we defined set B
Line 4: we used the symmetric_difference()
method to obtain the symmetric difference between the two sets by assigning a variable named symmetry
Line 5: we printed the output
Note: we can use another way to find the symmetric difference between two sets by using the
^
operator.
^
operator in PythonAs mentioned earlier, we can compute the symmetric difference between two sets by using the ^
operator. Therefore, let us find the symmetric difference between A and B sets using the ^
operator as follows:
A = {'a','b','c','d'}B = {'a','f','g'}# symmetric difference of two sets using ^ operatorprint(A ^ B)
The code above shows that without having to go through that method of symmetric_difference()
, one can easily use the ^
operator to compute the symmetric difference between two sets.