Write a Python program to Intersection of two lists


The program demonstrates the conversion of two lists a and b into sets x and y respectively, and then finding the intersection of two sets x and y. The set() method is used to convert the list into a set. The intersection() method is used to find the common elements in two sets and the result is stored in the variable n. Finally, the variable n is converted back to a list using the list() method and stored in the variable m.

Source Code

a = [1,2,3,4,5,6,7,8]
b = [11,2,43,48,55,6,76,8]
print("A :",a)
print("Type of A :",type(a))
print("B :",b)
print("Type of B :",type(b))
 
#Conver list to set
 
x = set(a)
y = set(b)
 
print("\nX :",x)
print("Type of X :",type(x))
print("Y :",y)
print("Type of Y :",type(y))
 
#Intersection of x and y
n = x.intersection(y)
m = list(n)
print("\nIntersection of Two Lists :",m)

Output

A : [1, 2, 3, 4, 5, 6, 7, 8]
Type of A : <class 'list'>
B : [11, 2, 43, 48, 55, 6, 76, 8]
Type of B : <class 'list'>

X : {1, 2, 3, 4, 5, 6, 7, 8}
Type of X : <class 'set'>
Y : {2, 6, 8, 43, 11, 76, 48, 55}
Type of Y : <class 'set'>

Intersection of Two Lists : [8, 2, 6]