Python Set symmetric_difference() method with examples
The Set update() method accepts another iterable such as Set, List, String, Dictionary as a parameter and adds the elements of these iterable to the calling set. This method converts the passed iterable to the set before adding their elements to the calling Set. For example – Lets say we have a Set A: {1, 2, 3} and a List lis: [2, “hello”] then calling A.update(lis) would update the set A and the elements of set A after update would be {1, 2, 3, “hello”}.
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))
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 Comment