Write a Python program to find the elements in a given set that are not in another set


This program demonstrates how to find the difference between two sets in Python. The code first declares two sets, x and y, containing integers. The sets are then printed to show their original values. Next, the difference between the sets x and y is found using two methods. The first method uses the difference() method, which takes one set as an argument and returns the set containing all the elements that are present in the original set but not present in the set passed as an argument. The second method uses the subtraction operator -, which has the same effect as the difference() method.

In both cases, the difference between x and y and the difference between y and x are found and stored in new sets. The contents of the sets are then printed. In this example, the difference between the sets x and y is the set {10, 20, 30, 40}, representing the elements that are present in x but not present in y. The difference between y and x is the set {80, 90, 100}, representing the elements that are present in y but not present in x.

Source Code

x = {10,20,30,40,50,60,70}
y = {50,60,70,80,90,100}
print("X : ",x)
print("Y : ",y)
 
print("\nFirst Method using difference()")
print("\n\tDifference of x and y :",x.difference(y))
print("\tDifference of y and x :",y.difference(x))
 
print("\nSecond Method Using operator(-)")
print("\n\tDifference of x and y :",x-y)
print("\tDifference of y and x :",y-x)
 

Output

X :  {50, 20, 70, 40, 10, 60, 30}
Y :  {80, 50, 100, 70, 90, 60}

First Method using difference()

        Difference of x and y : {40, 10, 20, 30}
        Difference of y and x : {80, 90, 100}

Second Method Using operator(-)

        Difference of x and y : {40, 10, 20, 30}
        Difference of y and x : {80, 90, 100}