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
Mary-Kate OlsenOriginal
2024-12-12 19:14:14775browse

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)

The expected output for this code is:

[1, 3, 5]

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!

Statement:
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