Find the Intersection of Two Lists in Python
To find the intersection of two lists in Python, you can use built-in functions like set()
and list comprehension. The intersection refers to the common elements present in both lists. Below, we explore multiple ways to achieve this.
Examples
1. Intersection of Two Lists using set.intersection()
Method
The intersection()
method of the set
class finds the common elements between two lists efficiently.
# Defining two lists
list1 = [1, 2, 3, 4, 5]
list2 = [4, 5, 6, 7, 8]
# Finding intersection using set.intersection()
intersection = list(set(list1).intersection(set(list2)))
# Printing the result
print("Intersection:", intersection)
Explanation:
- We convert both lists (
list1
andlist2
) into sets usingset()
. - We apply the
intersection()
method to find common elements. - The result is converted back into a list using
list()
to maintain list format.
Output:
Intersection: [4, 5]
2. Intersection of Two Lists using List Comprehension
List comprehension provides a concise way to filter common elements between two lists.
# Defining two lists
list1 = [10, 20, 30, 40, 50]
list2 = [30, 40, 60, 70]
# Finding intersection using list comprehension
intersection = [item for item in list1 if item in list2]
# Printing the result
print("Intersection:", intersection)
Explanation:
- We iterate through each element (
item
) inlist1
. - The condition
if item in list2
checks if the item also exists inlist2
. - If true, the item is added to the new list
intersection
.
Output:
Intersection: [30, 40]
3. Intersection of Two Lists using filter()
Function
The filter()
function can be used to filter elements present in both lists.
# Defining two lists
list1 = ["apple", "banana", "cherry", "mango"]
list2 = ["cherry", "grape", "apple"]
# Finding intersection using filter()
intersection = list(filter(lambda item: item in list2, list1))
# Printing the result
print("Intersection:", intersection)
Explanation:
1. The filter()
function applies a lambda function to each element in list1
.
2. The lambda function checks if the element is also in list2
.
3. Only elements satisfying the condition are returned and converted into a list.
Output:
Intersection: ['apple', 'cherry']
4. Intersection of Two Lists using set
and &
Operator
The &
operator is a shorthand for set intersection.
# Defining two lists
list1 = [5, 10, 15, 20, 25]
list2 = [15, 25, 35, 45]
# Finding intersection using & operator
intersection = list(set(list1) & set(list2))
# Printing the result
print("Intersection:", intersection)
Explanation:
- We convert both lists into sets.
- The
&
operator finds the common elements. - The result is converted back to a list.
Output:
Intersection: [25, 15]
Conclusion
Python provides multiple ways to find the intersection of two lists:
set.intersection()
: Efficient for large datasets.- List Comprehension: Simple and readable.
filter()
Function: Functional programming approach.&
Operator: Short and efficient.