Discover common elements in various lists

4

I have the following code:

list1 = ['a', 'x', 'c', 'b', 'm']
list2 = ['f', 'x', 'a', 'c']
list3 = ['c', 'e', 'x', 'b', 'p', 'k', 'l']

How do I find the common elements, so that I get a list like this:

comuns = ['x', 'c']
    
asked by anonymous 04.06.2016 / 11:50

1 answer

5

You can use sets and intersect them, sets are commonly used to prohibit duplicate values in a list, if you want to remove repeated values, make your list a set ( set(minha_lista) ). But in this case it is also to allow us to use the function intersection ( & ), as I do below. To declare a set syntactically is as it does with a dictionary but without assigning values to the keys ( meu_set = {1,2,3} ). Using sets in this type of operation is significantly faster than doing it directly in lists or dicts.

Note that the last two examples are to understand logic, do not use in real projects, just because it is more costly, slow, especially in large amounts of data.

Do this:

comuns = list(set(list1) & set(list2) & set(list3)) # ['x', 'c']

Or:

comuns = list(set(list1).intersection(list2).intersection(list3)) # ['x', 'c']

'Manually' would also give the normal structures (I do not recommend):

comuns = []
for i in list1:
    if(i in list2 and i in list3):
        comuns.append(i)

# comuns = ['x', 'c']

That using list comprehension would stay (I do not recommend):

comuns = [i for i in list1 if(i in list2 and i in list3)]

# comuns = ['x', 'c']
    
04.06.2016 / 11:58