I define intersection of two lists as follows:
def intersect(a, b):
return list(set(a) & set(b))
For three arguments it would look like:
def intersect(a, b, c):
return (list(set(a) & set(b) & set(c))
Can I generalize this function for variable number of lists?
The call would look for example like:
>> intersect([1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2])
[2]
EDIT: Python can only achieve it this way?
intersect([
[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]
])
[2]
Intersection of two list means we need to take all those elements which are common to both of the initial lists and store them into another list.
Step1: input the elements of three lists. Step2: Use intersection method, first convert lists to sets then apply intersection method of two sets and find out common elements then this set intersect with the third set.
To count the intersection of sets in Python, we will use “len(set(set1) & set(set2))”. Here, ” & “ is an intersection element common to both. It will return the count as “3” because “10, 8, and 6” are common to both the sets. In this output, we can see python count intersection of sets is performed.
Use the *
-list-to-argument operator and instead of your custom function use set.intersection
:
>>> lists = [[1, 2, 2], [2, 3, 2], [2, 5, 2], [2, 7, 2]]
>>> list(set.intersection(*map(set, lists)))
[2]
If you want the list-to-set-to-list logic inside a function, you can do it like this:
def intersect(lists):
return list(set.intersection(*map(set, lists)))
If you prefer intersect()
to accept an arbitrary number of arguments instead of a single one, use this instead:
def intersect(*lists):
return list(set.intersection(*map(set, lists)))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With