Write a Python program to create a symmetric difference


This program demonstrates the use of symmetric differences in Python. Sets are unordered collections of unique elements, and symmetric differences are used to find the elements that are unique to each set. The code first declares two sets, a and b, containing integers. The sets are then printed to show their original values.

Next, the code demonstrates how to find the symmetric difference between two sets, which is a set that contains all of the elements that are unique to each set. The symmetric difference between two sets is the set of elements that are present in one set but not present in the other.

The symmetric difference between the sets a and b is found using the symmetric_difference() method. This method takes one set as an argument and returns the symmetric difference between the two sets. The result is stored in two new sets, res1 and res2, representing the symmetric difference between a and b and between b and a respectively. The contents of the sets are then printed.

In this example, the symmetric difference between the sets a and b is the set {70, 30, 80, 10, 90, 60}, representing the elements that are unique to each set. The symmetric difference between b and a is also the set {70, 30, 80, 10, 90, 60}, representing the elements that are unique to each set, which are the same as the symmetric difference between a and b.

Source Code

a = {30,40,70,20,80,50}
b = {20,50,60,40,90,10}
print("Original sets:")
print("A :",a)
print("B : ",b)
res1 = a.symmetric_difference(b)
print("\nSymmetric Difference of a - b:",res1)
res2 = b.symmetric_difference(a)
print("\nSymmetric Difference of b - a:",res2)

Output

Original sets:
A : {80, 50, 20, 70, 40, 30}
B :  {50, 20, 90, 40, 10, 60}

Symmetric Difference of a - b: {70, 10, 80, 90, 60, 30}

Symmetric Difference of b - a: {70, 10, 80, 90, 60, 30}