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 :
Intersection of two list means taking out the common elements from two lists. In the image below description of intersection is shown :
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=[1, 2, 3, 4, 5, 6, 7, 4] list2=[2, 4, 6, 8, 10, 4 ] #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 listIntersection( lst1, lst2 ): return [value for value in lst1 if value in lst2] list1=[1, 2, 3, 4, 5, 6, 7, 4] list2=[2, 4, 6, 8, 10, 4 ] #calling function listIntersection() print(listIntersection(list1,list2))
Output : [2, 4, 6, 4]
Prime Course Trailer
Related Banners
Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription
Get over 200+ course One Subscription
Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others
Login/Signup to comment