Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find common values in multiple lists [duplicate]

Tags:

python

list

So I have lists of numbers, and I would like to find numbers that exist in all the lists. I prefer not to use loop if possible.

Here is one example

a = [1, 2, 3, 4]
b = [2, 3, 4, 5, 6]
c = [3, 4, 5, 6, 10, 12]
df['A'] = [a, b, c]

The output is expected to be

[3, 4]

My problem here is, the number of lists is not given and not fixed. It can be about 20 lists with different lengths (e.g. [a, b, c, d, e, g, ..., l])

I have seen answers using set(a) & set(b) & set(c), but I am not sure how to apply this in my case.

like image 308
SSS Avatar asked Dec 01 '22 09:12

SSS


2 Answers

You could use map along with set.intersection:

>>> a = [1, 2, 3, 4]
>>> b = [2, 3, 4, 5, 6]
>>> c = [3, 4, 5, 6, 10, 12]
>>> elements_in_all = list(set.intersection(*map(set, [a, b, c])))
>>> elements_in_all
[3, 4]
like image 91
Sash Sinha Avatar answered Dec 03 '22 23:12

Sash Sinha


I'm not sure why you'd want to avoid loops, since that's .. really what you're asking for - looping over a list of lists and keeping the set of unique values.

l = [a, b, c]
s = None

for e in l:
  if not s:
    s = set(e)
  else:
    s &= set(e)

s => set([3, 4])

You can also create a functional version that doesn't explicitly use loops, and still support an arbitrary number of arguments:

reduce((lambda x,y: x & y), map(set, l))

First, convert every list in your containing list l to a set, then use reduce to apply the intersection for each element contained - the result is a single set with the elements common to all lists.

like image 36
MatsLindh Avatar answered Dec 03 '22 23:12

MatsLindh