Write a Python program to create set difference


This program demonstrates the use of set differences in Python. Sets are unordered collections of unique elements, and set differences are used to find the elements in one set that are not present in another 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 difference between two sets, which is a set that contains all of the elements that are present in one set but not present in the other.

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

In this example, the difference between the sets a and b is the set {70, 30, 80}, representing the elements that are present in a but not present in b. The difference between b and a is the set {90, 10}, representing the elements that are present in b but not present in a.

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.difference(b)
print("\nDifference of a - b:",res1)
res2 = b.difference(a)
print("\nDifference of b - a:",res2)

Output

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

Difference of a - b: {80, 70, 30}

Difference of b - a: {90, 10, 60}