Intersection of Two Lists in Python

Intersection of Two Lists

 

Intersection of two lists means  fetching all the elements which is present in both of the initial lists i.e. fetching all the common elements from both lists and store it into another list.

There are certain ways of finding intersection of two lists in python is explained in this page.

Intersection of Two Lists in Python

Example :

A = [ 100, 200, 300, 454 ]

B = [100, 150, 200 ]

Since elements 100 and 200 are common in both list

A ∩ B = [ 100, 200 ]

Method 1 : By converting Lists into Sets


list1=[12345674]
list2=[2468104 ]

#convert list1 as a set and then use intersection()
print(list(set(list1).intersection(list2)))

#convert both list1 and list2 as a set and then use intersection()
print(list(set(list1).intersection(set(list2))))


Output :

[2, 4, 6]
[2, 4, 6]

In Method 1, the list is converted into set because of which multiple appearances of same value element is removed and we did not get that elements in the output list. We can solve this issue by Method 2.

Method 2 : Creating a function


#function for Intersection
def listIntersectionlst1lst2 ):
    return [value for value in lst1 if value in lst2]


list1=[12345674]
list2=[2468104 ]

#calling function listIntersection()
print(listIntersection(list1,list2))


Output :

[2, 4, 6, 4]