Home >Backend Development >Python Tutorial >How Can We Find the Intersection of Two Lists?
Intersection of Lists
Given two lists, how can we find their intersection, which is a list of elements that are present in both lists?
In the example provided, we have two lists:
a = [1,2,3,4,5] b = [1,3,5,6]
The expected output is the intersection of these two lists, which should be:
[1,3,5]
Using Set Intersection
One way to find the intersection of two lists is to use set intersection. Sets are unordered collections of unique elements, so using set intersection can help eliminate duplicates. Here's how we can use it:
a = [1,2,3,4,5] b = [1,3,5,6] result = list(set(a) & set(b)) print(result) # [1, 3, 5]
In this code, we convert both lists into sets using the set() function. Then, we use the & operator to perform set intersection. The result is converted back to a list using the list() function. This gives us the desired intersection of the two lists.
The above is the detailed content of How Can We Find the Intersection of Two Lists?. For more information, please follow other related articles on the PHP Chinese website!