Skip to content
Related Articles

Related Articles

Python | Intersection of multiple lists

View Discussion
Improve Article
Save Article
  • Last Updated : 25 Apr, 2019
View Discussion
Improve Article
Save Article

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 : Naive(List comprehension)

The brute-force or naive approach to find the intersection of list of lists is to use List comprehension or simply a for loop.




# Python3 program to find 
# Intersection of list of lists
  
def intersection(lst1, lst2):
      
    return [item for item in lst1 if item in lst2]
              
# Driver code
lst1 = [['a', 'c'], ['d', 'e']]
lst2 = [['a', 'c'], ['e', 'f'], ['d', 'e']]
print(intersection(lst1, lst2))

Output:

[['a', 'c'], ['d', 'e']]

 
Approach #2 : Using Set intersection()

This is an efficient method in comparison to the naive approach. We first convert both list of lists into list of tuples using map() because Python sets are compatible with tuples, not lists. Then we simply find Set intersection() of both the lists.




# Python3 program to find 
# Intersection of list of list
  
def intersection(lst1, lst2):
    tup1 = map(tuple, lst1)
    tup2 = map(tuple, lst2) 
    return list(map(list, set(tup1).intersection(tup2)))
              
# Driver code
lst1 = [['a', 'c'], ['d', 'e']]
lst2 = [['a', 'c'], ['e', 'f'], ['d', 'e']]
print(intersection(lst1, lst2))

Output:

[['d', 'e'], ['a', 'c']]

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!