Set symmetric_difference() method returns a symmetric difference of two given sets. A symmetric difference of two sets X and Y contains the elements that are in either set X or Set Y but not in both. For example – symmetric difference of set {1, 2, 3} and {2, 3, 4} would be {1, 4} because elements 2 and 3 are present in both the sets.
Set symmetric_difference() syntax
set.symmetric_difference(another_set)
Parameter: It takes a set as a parameter
Return Value: It returns a new set which is a symmetric difference of the two given sets.
Python Set symmetric_difference() Example
In the following example we have three sets X, Y and Z. Sets Y and Z are same. When we find the symmetric difference between same sets it returns nothing, as shown in the output of the following example. We can also find the symmetric difference using ^ operator, which is discussed in the next section of this same article.
# Set X X = {1, 2, 3} # Set Y Y = {2, 3, 4} # Set Z Z = {2, 3, 4} print("Symmetric difference between X & Y", X.symmetric_difference(Y)) print("Symmetric difference between Y & Z", Y.symmetric_difference(Z)) print("Symmetric difference between X & X", X.symmetric_difference(X))
Output:
Finding the symmetric difference between two sets using ^ operator
We can use the ^ operator instead of symmetric_difference() method to find the symmetric difference between two sets as shown in the following example.
# Set X X = {1, 2, 3} # Set Y Y = {2, 3, 4} # Set Z Z = {2, 3, 4} print(X^Y) print(X^Z) print(Y^Z) # symmetric difference with self print(X^X) print(Y^Y)
Output:
{1, 4} {1, 4} set() set() set()
Leave a Reply