Home > Backend Development > Python Tutorial > How Can We Find the Intersection of Two Lists?

How Can We Find the Intersection of Two Lists?

DDD
Release: 2024-12-07 12:40:14
Original
904 people have browsed it

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]
Copy after login

The expected output is the intersection of these two lists, which should be:

[1,3,5]
Copy after login

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]
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template