Intersection of Two Lists - Python
Given two lists, the task is to find the elements that appear in both of them. For Example:
Input: A = [4, 9, 1, 17, 11], B = [9, 74, 21, 45]
Output: [9]
Explanation: 9 is the only value present in both lists.
Let's explore different methods to find the intersection of two lists using Python.
Using Set
This method finds common elements by converting both lists into sets. Since sets store unique elements, performing a set intersection directly gives the shared values between both lists.
a = [4, 9, 1, 17, 11, 26, 28, 54, 69]
b = [9, 9, 74, 21, 45, 11, 63, 28, 26]
res = list(set(a) & set(b))
print(res)
Output
[9, 26, 11, 28]
Explanation:
- set(a) and set(b) remove duplicates.
- The & operator returns elements present in both sets.
Using set.intersection()
This method also converts both lists into sets and uses the built-in .intersection() method to obtain values that appear in both sets.
a = [4, 9, 1, 17, 11, 26, 28, 54, 69]
b = [9, 9, 74, 21, 45, 11, 63, 28, 26]
res = list(set(a).intersection(set(b)))
print(res)
Output
[9, 26, 11, 28]
Explanation: .intersection() returns only the elements that exist in both sets.
Using Counter
This method counts how many times each value appears in both lists and keeps only the elements with matching counts. It is useful when the intersection should respect duplicates.
from collections import Counter
a = [4, 9, 1, 17, 11, 26, 28, 54, 69]
b = [9, 9, 74, 21, 45, 11, 63, 28, 26]
res = list((Counter(a) & Counter(b)).elements())
print(res)
Output
[9, 11, 26, 28]
Explanation:
- Counter(a) & Counter(b) keeps the minimum frequency of each common element.
- .elements() returns those elements accordingly.
Using List Comprehension
This method checks each element in the first list and keeps it only if that value also exists in the second list.
a = [4, 9, 1, 17, 11, 26, 28, 54, 69]
b = [9, 9, 74, 21, 45, 11, 63, 28, 26]
res = [x for x in a if x in b]
print(res)
Output
[9, 11, 26, 28]
Explanation: x in b checks if each value of list a is also present in list b, and only those values are added to the result.