Intersection of lists in python

In this example, We will define two lists and find overlap list using different methods.

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. There are various ways to overlap or intersection list in python.

Method 1 : Intersection lists with set() function

Intersection of list with set() function,

Example :

    
#Intersection of two list with set method
def overlap(l1, l2):
    return list(set(l1) & set(l2))

l1 = [17,51,39,12,63,55,77,45,96,85]
l2 = [9, 4, 25, 51, 96, 26, 10, 45, 87]
print(overlap(l1, l2))
    

Output :

    
[96, 51, 45]
    

Method 2 : Intersection lists with set() and intersection()

In this method, we will use set() function with intersection() function to find Overlaping list. Here set and intersection both are built-in functions.

Example :

    
#Intersection two list with set and intersection
def overlap(l1, l2):
    return set(set(l1).intersection(l2))

l1 = [17,51,39,12,63,55,77,45,96,85]
l2 = [9, 4, 25, 51, 96, 26, 10, 45, 87]
print(overlap(l1, l2))
    

Output :

    
{96, 51, 45}
    

Method 3 : Intersection lists with filter() function

Filter in python is an inbuilt function that is used to filter out elements from a given list. We pass each element from the list to the given function. Only those elements will be included for which the function returns True value.

Example :

    
#Intersection two list with filter function
def overlap(l1, l2):
    return list(filter(lambda x: x in l1, l2)) 

l1 = [17,51,39,12,63,55,77,45,96,85]
l2 = [9, 4, 25, 51, 96, 26, 10, 45, 87]
print(overlap(l1, l2))
    

Output :

    
[96, 51, 45]
    

Method 4 : Intersection Lists with numpy.intersect1d()

We can also use the intersect1d() function present in the numpy library to achieve a list intersection. We will pass two lists as arguments, and it will return the unique values from both lists in a sorted manner. The output will then be explicitly converted to a list using the list() function.

Example :

    
#Overlap two list with numpy.intersect1d
import numpy as np
l1 = [17,51,39,12,63,55,77,45,96,85]
l2 = [9, 4, 25, 51, 96, 26, 10, 45, 87]
print(list(np.intersect1d(A, B)))
    

Output :

    
[45, 51, 96]
    

Method 5 : Creating a user defined function

We can also build a user-defined function for performing intersection. If an element exists in list1, we will append that element in a new list ‘intersect’ if it is present in list2 too. We achieve this using for loop and if statement.

Example :

    
#Overlap two list with custom logic
def overlap(l1, l2):
    intersect = []
    for i in l1:
        if i in l2:
            intersect.append(i)
    return intersect
l1 = [17,51,39,12,63,55,77,45,96,85]
l2 = [9, 4, 25, 51, 96, 26, 10, 45, 87]
print(overlap(l1, l2))
    

Output :

    
[51, 45, 96]
    

Share your thoughts

Ask anything about this examples