Write a Python program to create an intersection of sets


This program demonstrates the use of set intersections in Python. Sets are unordered collections of unique elements, and set intersections are used to find the common elements between two sets.

  • 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 two methods for finding the intersection of the two sets, which is the set of elements that are common to both sets.
  • The first method is using the & operator, which returns the intersection of two sets. This is stored in a new set, c. The contents of c are then printed.
  • The second method is using the intersection() method, which takes one set as an argument and returns the intersection of the two sets. This is stored in a new set, d, and its contents are then printed.

In this example, both methods produce the same result, which is the set {40, 20}, representing the common elements between the two sets a and b.

Source Code

a = {30,40,70,20}
b = {20,50,60,40}
print("Original set Values :")
print(a)
print(b)
print("\nIntersection of two Sets:")
#First Method
c = a & b
print(c)
#Second Method
d=a.intersection(b)
print(d)
 

Output

Original set Values :
{40, 20, 70, 30}
{40, 50, 20, 60}

Intersection of two Sets:
{40, 20}
{40, 20}