Home >Backend Development >Python Tutorial >How to Find the Intersection of Multiple Lists within a List in Python?
Finding the Intersection of Multiple Lists in Python
In Python, determining the intersection of two lists is straightforward using the set.intersection() method. However, the question arises: how do we find the intersection of multiple lists within a list?
Consider the scenario where we have a list of lists, aptly named d, containing three elements a, b, and c, as shown below:
<code class="python">d = [[1, 2, 3, 4], [2, 3, 4], [3, 4, 5, 6, 7]]</code>
To determine the intersection of all three lists, we can leverage Python's set.intersection() method and the map() function. The map() function takes two arguments: a function and an iterable. In this case, we apply the map() function with the set() function to convert each list element in d into a set. The resulting output is a list of sets.
Finally, we utilize the set.intersection() method to compute the intersection of these sets, effectively finding the intersection of all three lists within d.
<code class="python">intersection = set.intersection(*map(set, d))</code>
By executing this code, we obtain the desired intersection:
<code class="python">print(intersection) # Output: {3, 4}</code>
Therefore, even when dealing with multiple lists within a list, Python provides a concise solution for determining their intersection using the set.intersection() method in conjunction with the map() function.
The above is the detailed content of How to Find the Intersection of Multiple Lists within a List in Python?. For more information, please follow other related articles on the PHP Chinese website!