How to Find the Intersection of Multiple Lists in Python?

Patricia Arquette
Release: 2024-10-21 22:04:03
Original
234 people have browsed it

How to Find the Intersection of Multiple Lists in Python?

Python: Intersecting Multiple Lists

When working with multiple lists, finding their common elements can be a valuable operation. While Python provides a convenient function for intersecting two lists (set(a).intersection(b)), the task becomes slightly more complex when dealing with more than two lists.

Let's consider a scenario where we have a list of lists d containing several lists (in your example, d = [[1,2,3,4], [2,3,4], [3,4,5,6,7]]). To find the intersection of all the lists within d, we can leverage Python's set operations and built-in functions.

One approach is to use the set.intersection() method repeatedly. However, this method only operates on two sets at a time, so we need to apply it iteratively. Here's how we can do it:

<code class="python">intersection = set(d[0])
for lst in d[1:]:
    intersection = intersection.intersection(set(lst))

print(intersection)  # Outputs: {3, 4}</code>
Copy after login

Another concise and efficient solution utilizes Python's * operator and the map() function:

<code class="python">intersection = set.intersection(*map(set, d))

print(intersection)  # Outputs: {3, 4}</code>
Copy after login

In this solution, we use the map() function to convert each list in d into a set. The * operator then unpacks this sequence of sets into the arguments of set.intersection(), allowing us to find the intersection of all the sets simultaneously.

Both of these approaches effectively find the intersection of multiple lists stored within a list of lists. By leveraging Python's set operations, we can easily identify the common elements among any number of lists.

The above is the detailed content of How to Find the Intersection of Multiple Lists in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!