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

How Can I Find the Intersection of Two Lists in Python?

Mary-Kate Olsen
Release: 2024-12-12 19:14:14
Original
714 people have browsed it

How Can I Find the Intersection of Two Lists in Python?

Accessing List Intersections

To retrieve the intersection of two lists, commonly referred to as a boolean AND operation, there are various approaches. One straightforward method is to utilize set intersection. This approach disregards order and duplicates, ensuring that only common elements are included in the result.

To employ this technique, begin by converting the lists to sets using the set() function. Then, perform a set intersection operation using the & operator. Finally, convert the resulting set back to a list using the list() function. This process yields a list containing only the elements present in both the original lists.

Consider the following example:

a = [1,2,3,4,5]
b = [1,3,5,6]
c = list(set(a) & set(b))
print(c)
Copy after login

The expected output for this code is:

[1, 3, 5]
Copy after login

The above is the detailed content of How Can I Find the Intersection of Two Lists in Python?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template