Last modified: Oct 31, 2024 By Alexander Williams
Python Find Common Elements in Two Lists
Finding elements that exist in both lists is common in Python, whether for data analysis or filtering.
This guide will show different ways to get common elements from two lists.
Using set() Intersection
The simplest way to find common elements is using set()
intersection.
This method is efficient and best for unique elements.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common_elements = list(set(list1) & set(list2))
print(common_elements)
[3, 4]
Using set()
with the &
operator returns a list of unique common items.
Using List Comprehension
If order matters or you need duplicate values, use list comprehension.
This method keeps duplicates and order from list1
.
list1 = [1, 2, 2, 3, 4]
list2 = [2, 3, 5, 6]
common_elements = [x for x in list1 if x in list2]
print(common_elements)
[2, 2, 3]
With list comprehension
, common_elements
includes all occurrences from list1
.
Using the filter() Function
The filter()
function provides a concise way to filter common elements with a condition.
It's an alternative to list comprehension for readability.
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common_elements = list(filter(lambda x: x in list2, list1))
print(common_elements)
[3, 4]
In this example, filter()
checks if each item in list1
is in list2
.
Using numpy.intersect1d() for Array Intersections
For those working with large data or numerical lists, numpy.intersect1d()
from the NumPy library is highly efficient.
This function returns the sorted, unique values present in both lists.
import numpy as np
list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
common_elements = np.intersect1d(list1, list2)
print(common_elements)
[3 4]
Using numpy.intersect1d()
returns a NumPy array of unique common items.
Conclusion
In Python, you can find common elements with set()
intersection, list comprehension, and even numpy
.
For more list operations, see Python Filter List: A Complete Guide.
Choose the method that best suits your needs, considering performance and list characteristics.