Open In App

Python | Intersection of two lists

Last Updated : 23 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list. Now there are various ways in Python, through which we can perform the Intersection of the lists. 
Examples: 
 

Input : 
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
Output :
[9, 10, 4, 5]

Input :
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
Output :
[9, 11, 26, 28]

 

Method 1: 
This is the simplest method where we haven’t used any built-in functions. 
 

Python3




# Python program to illustrate the intersection
# of two lists in most simple way
def intersection(lst1, lst2):
    lst3 = [value for value in lst1 if value in lst2]
    return lst3
 
# Driver Code
lst1 = [4, 9, 1, 17, 11, 26, 28, 54, 69]
lst2 = [9, 9, 74, 21, 45, 11, 63, 28, 26]
print(intersection(lst1, lst2))


Output: 
 

[9, 11, 26, 28]

Method 2: 
This method includes the use of set() method
 

Python3




# Python program to illustrate the intersection
# of two lists using set() method
def intersection(lst1, lst2):
    return list(set(lst1) & set(lst2))
 
# Driver Code
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
print(intersection(lst1, lst2))


Output: 
 

[9, 10, 4, 5]

The time complexity of the above program is O(n), where n is the length of the longer list between lst1 and lst2.

The space complexity of the program is O(n), where n is the length of the smaller list between lst1 and lst2. 

Method 3: 
In this method we set() the larger list and then use the built-in function called intersection() to compute the intersected list. intersection() is a first-class part of set. 
 

Python3




# Python program to illustrate the intersection
# of two lists using set() and intersection()
def Intersection(lst1, lst2):
    return set(lst1).intersection(lst2)
     
# Driver Code
lst1 = [ 4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
lst2 = [9, 9, 74, 21, 45, 11, 63]
print(Intersection(lst1, lst2))


Output: 
 

{9, 11}

Method 4: 
By the use of this hybrid method the complexity of the program falls to O(n). This is an efficient way of doing the following program. 
 

Python3




# Python program to illustrate the intersection
# of two lists
def intersection(lst1, lst2):
 
    # Use of hybrid method
    temp = set(lst2)
    lst3 = [value for value in lst1 if value in temp]
    return lst3
 
# Driver Code
lst1 = [9, 9, 74, 21, 45, 11, 63]
lst2 = [4, 9, 1, 17, 11, 26, 28, 28, 26, 66, 91]
print(intersection(lst1, lst2))


Output: 
 

[9, 9, 11]

Method 5: 
This is the where the intersection is performed over sub-lists inside other lists. Here we have used the concept of filter(). 
 

Python3




# Python program to illustrate the intersection
# of two lists, sublists and use of filter()
def intersection(lst1, lst2):
    lst3 = [list(filter(lambda x: x in lst1, sublist)) for sublist in lst2]
    return lst3
 
# Driver Code
lst1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
lst2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
print(intersection(lst1, lst2))


Working: The filter part takes each sublist’s item and checks to see if it is in the source list. The list comprehension is executed for each sublist in list2. 
Output: 
 

[[13, 32], [7, 13, 28], [1, 6]]

Method 6: Using reduce():
Algorithm:

  1. Import the reduce function from functools module.
  2. Define two lists.
  3. Initialize the variable intersection with an empty list.
  4. Use the reduce function to iterate over the elements of lst1.
  5. Inside the lambda function, check if the current element is present in lst2 and not already present in the intersection list.
  6. If it is, then add the current element to the intersection list.
  7. Return the intersection list.
  8. Print the intersection list.

Python3




from functools import reduce
 
lst1 = [15, 9, 10, 56, 23, 78, 5, 4, 9]
lst2 = [9, 4, 5, 36, 47, 26, 10, 45, 87]
 
intersection = reduce(lambda acc, x: acc + [x] if x in lst2 and x not in acc else acc, lst1, [])
 
print(intersection)
#This code is contributed by Rayudu.


Output

[9, 10, 5, 4]

Time Complexity: O(n^2), where n is the length of lst1.
Space Complexity: O(n), where n is the length of lst1.
 



Similar Reads

Python Program For Finding Intersection Point Of Two Linked Lists
There are two singly linked lists in a system. By some programming error, the end node of one of the linked list got linked to the second list, forming an inverted Y-shaped list. Write a program to get the point where two linked lists merge.  Above diagram shows an example with two linked lists having 15 as intersection points. Recommended: Please
6 min read
Python Program For Finding Intersection Of Two Sorted Linked Lists
Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory — the original lists should not be changed.  Example:  Input: First linked list: 1->2->3->4->6 Second linked list be 2->4->6->8, Output: 2->4->6. The elements 2, 4, 6 are common in
4 min read
Python | Intersection of multiple lists
Given two list of lists, write a Python program to find the intersection between the given two lists. Examples: Input : lst1 = [['a', 'c'], ['d', 'e']] lst2 = [['a', 'c'], ['e', 'f'], ['d', 'e']] Output : [['a', 'c'], ['d', 'e']] Input : lst1 = [[1, 5, 7], [2, 3], [6, 9], [4, 8]] lst2 = [[9, 3], [2, 3], [6, 9]] Output : [[2, 3], [6, 9]] Approach #1
5 min read
How to Zip two lists of lists in Python?
The normal zip function allows us the functionality to aggregate the values in a container. But sometimes, we have a requirement in which we require to have multiple lists and containing lists as index elements and we need to merge/zip them together. This is quite uncommon problem, but solution to it can still be handy. Let's discuss certain ways i
7 min read
Intersection of two arrays in Python ( Lambda expression and filter function )
Given two arrays, find their intersection. Examples: Input: arr1[] = [1, 3, 4, 5, 7] arr2[] = [2, 3, 5, 6] Output: Intersection : [3, 5] We have existing solution for this problem please refer Intersection of two arrays link. We will solve this problem quickly in python using Lambda expression and filter() function. Implementation: C/C++ Code # Fun
1 min read
Python | Intersection of two String
One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings. There are various ways in Python, through which we can perform the Intersection of two strings. Method #1 : Naive Method Create an empty string and check for new occurrence of character common to both string a
3 min read
Python | Intersection of two nested list
This particular article aims at achieving the task of intersecting two list, in which each element is in itself a list. This is also a useful utility as this kind of task can come in life of programmer if he is in the world of development. Lets discuss some ways to achieve this task. Method 1: Naive Method This is the simplest method to achieve thi
5 min read
Intersection of two dataframe in Pandas - Python
Intersection of Two data frames in Pandas can be easily calculated by using the pre-defined function merge(). This function takes both the data frames as argument and returns the intersection between them. Syntax: pd.merge(df1, df2, how) Example 1: import pandas as pd # Creating Data frames df1 = {'A': [1, 2, 3, 4], 'B': ['abc', 'def', 'efg', 'ghi'
1 min read
Python | Program to count number of lists in a list of lists
Given a list of lists, write a Python program to count the number of lists contained within the list of lists. Examples: Input : [[1, 2, 3], [4, 5], [6, 7, 8, 9]] Output : 3 Input : [[1], ['Bob'], ['Delhi'], ['x', 'y']] Output : 4 Method #1 : Using len() C/C++ Code # Python3 program to Count number # of lists in a list of lists def countList(lst):
5 min read
Python - Convert Lists into Similar key value lists
Given two lists, one of key and other values, convert it to dictionary with list values, if keys map to different values on basis of index, add in its value list. Input : test_list1 = [5, 6, 6, 6], test_list2 = [8, 3, 2, 9] Output : {5: [8], 6: [3, 2, 9]} Explanation : Elements with index 6 in corresponding list, are mapped to 6. Input : test_list1
12 min read
Practice Tags :
three90RightbarBannerImg