In this short guide, I’ll show you how to find the intersection of two lists in python. So without further ado let’s get started.
Our main aim is to find common elements that occur in both lists. for example :
# Input l1 = [1,2,3,4,5,5] l2 = [4,5,7,8] # Output : [4,5]
1. By Using For Loop
In this code example, we have used for loop to find intersection of two lists in python.
Here is the algorithm.
- We first define an empty list to store the result.
- To remove duplicates from the first input list we convert it into the set.
- Then we iterate through the set.
- On each iteration, we check if the element also exists inside the second list then we add it to the result list.
# python program to find the intersection of two lists in python l1 = [1,2,3,4,5,5] l2 = [4,5,7,8] intersection =  # Empty result list set_l1 = set(l1) # convert it to set for i in set_l1 : # iterate through the set if i in l2: # check if i exists inside the l2 intersection.append(i) # add it the result print(intersection)
Here is the output of the above code.
2. By Using Sets
The set data type of python is the mathematical notion of a set that automatically removes the duplicates during its initialization.
In the below code, we first convert both lists to set and take its intersection.
# Program to take intersection of two lists in python by using sets l1 = [1,2,3,4,5,5] l2 = [4,5,7,8] intersection = list(set(l1) & set(l2)) print(intersection)
3. By Using List-Comps
This code example is the same as the first example. But instead of using for loop, we have reduced the number of lines of code by using the list comprehension.
l1 = [1,2,3,4,5,5] l2 = [4,5,7,8] intersection = [i for i in set(l1) if i in l2] print(intersection)
Also read about how to reverse a list in python