Open In App

Python | Intersection of two nested list

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 this task and uses the brute force approach of executing a loop and to check if one list contains similar list as of the other list. 

Python3




# Python 3 code to demonstrate
# find intersection of nested list
# using naive method
 
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
 
# printing both lists
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
 
# using naive method
# to get list intersection
res_list = []
for i in test_list1:
    if i in test_list2:
        res_list.append(i)
 
# printing the intersection
print ("The intersection of two lists is : " + str(res_list))


Output :

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method 2: Using list comprehension We can perform the similar task as discussed above in comparatively less no. of lines. But the method is similar as above just uses list comprehension approach to perform the task. 

Python3




# Python 3 code to demonstrate
# find intersection of nested list
# using list comprehension
 
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
 
# printing both lists
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
 
# using list comprehension
# to get list intersection
res_list = [i for i in test_list1 if i in test_list2]
 
# printing the intersection
print ("The intersection of two lists is : " + str(res_list))


Output :

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]

Time Complexity: O(n2)
Auxiliary Space: O(n)

Method 3: Using set() + map() and & The most efficient and recommended method to perform this task is using the combination of set() and map() to achieve it. Firstly converting inner lists to tuples using map, and outer lists to set, use of & operator can perform the set intersection and hence perform this task. Further if it is required to get in lists of list fashion, we can convert outer and inner containers back to list using map(). 

Python3




# Python 3 code to demonstrate
# find intersection of nested list
# using map() + set() + &
 
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
 
# printing both lists
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
 
# using map() + set() + &
# to get list intersection
res_set = set(map(tuple, test_list1)) & set(map(tuple, test_list2))
res_list = list(map(list, res_set))
 
# printing the intersection
print ("The intersection of two lists is : " + str(res_list))


Output :

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]

Time Complexity: O(n)
Auxiliary Space: O(n)

Method 4: Using filter() and lambda function

  • Convert both nested lists into sets using map() and set().
  • Create a lambda function that takes a nested list and returns True if it’s a subset of the second set.
  • Use filter() with the lambda function to get a filter object of the subsets.
  • Convert the filter object to a list using list().
  • Print the resulting list.

Python3




# Python 3 code to demonstrate
# find intersection of nested list
# using filter() and lambda function
 
# initializing lists
test_list1 = [ [1, 2], [3, 4], [5, 6] ]
test_list2 = [ [3, 4], [5, 7], [1, 2] ]
 
# printing both lists
print ("The original list 1 : " + str(test_list1))
print ("The original list 2 : " + str(test_list2))
 
# using filter() and lambda function
# to get list intersection
set1 = set(map(tuple, test_list1))
set2 = set(map(tuple, test_list2))
intersection_list = list(filter(lambda x: tuple(x) in set2, test_list1))
 
# printing the intersection
print ("The intersection of two lists is : " + str(intersection_list))
 
#


Output

The original list 1 : [[1, 2], [3, 4], [5, 6]]
The original list 2 : [[3, 4], [5, 7], [1, 2]]
The intersection of two lists is : [[1, 2], [3, 4]]

Time Complexity: O(n^2), where n is the length of the nested lists.
Auxiliary Space: O(k), where k is the size of the intersection list.



Previous Article
Next Article

Similar Reads

python | Nested List Intersection Matrix Product
The problem of finding the common elements in list of 2 lists is quite a common problem and can be dealt with ease and also has been discussed before many times. But sometimes, we require to find the elements that are in common from N lists and return their product. Let’s discuss certain ways in which this operation can be performed. Method #1 : Us
3 min read
Python | Check if a nested list is a subset of another nested list
Given two lists list1 and list2, check if list2 is a subset of list1 and return True or False accordingly. Examples: Input : list1 = [[2, 3, 1], [4, 5], [6, 8]] list2 = [[4, 5], [6, 8]] Output : True Input : list1 = [['a', 'b'], ['e'], ['c', 'd']] list2 = [['g']] Output : False Let's discuss few approaches to solve the problem. Approach #1 : Naive
7 min read
Python | Intersection of two lists
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
4 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
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 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 | Split nested list into two lists
Given a nested 2D list, the task is to split the nested list into two lists such that the first list contains the first elements of each sublist and the second list contains the second element of each sublist. In this article, we will see how to split nested lists into two lists in Python. Python Split Nested List into Two ListsBelow are the ways b
5 min read
Python - Tuple List intersection (Order irrespective)
Given list of tuples, perform tuple intersection of elements irrespective of their order. Input : test_list1 = [(3, 4), (5, 6)], test_list2 = [(5, 4), (4, 3)] Output : {(3, 4)} Explanation : (3, 4) and (4, 3) are common, hence intersection ( order irrespective). Input : test_list1 = [(3, 4), (5, 6)], test_list2 = [(5, 4), (4, 5)] Output : set() Exp
6 min read
Practice Tags :