Home >Backend Development >Python Tutorial >How Can I Find Common Elements Between Two Lists in Python?
In Python, comparing two lists to find the common elements can be achieved using various approaches. Let's explore them:
Method 1: Using Set Intersection
This method converts the lists to sets, which are unordered collections of unique elements. Intersecting these sets using the & operator provides the values that appear in both lists.
a = [1, 2, 3, 4, 5] b = [9, 8, 7, 6, 5] result = set(a) & set(b) # result: {5}
Method 2: Using List Comprehension
This method iterates over pairs of elements from both lists using the zip function. It creates a new list containing only the elements that are equal in both lists.
result = [i for i, j in zip(a, b) if i == j] # result: [5]
Method 3: Using Counter
The collections.Counter class can be used to count the occurrences of elements in both lists. The intersection method of the Counter object returns a new Counter object with the matching elements.
import collections a_counter = collections.Counter(a) b_counter = collections.Counter(b) result = a_counter & b_counter # result: Counter({5: 1})
The above is the detailed content of How Can I Find Common Elements Between Two Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!