Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intersection of variable number of lists

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]
like image 546
xralf Avatar asked Jun 02 '12 09:06

xralf


People also ask

What is intersection of lists?

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.

How do you find the intersection of three lists in Python?

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.

How do you find the intersection of a list set in Python?

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.


1 Answers

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)))
like image 61
ThiefMaster Avatar answered Nov 15 '22 16:11

ThiefMaster