Discover common elements in multiple lists

Asked

Viewed 1,118 times

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 discover the common elements so that you have a list like this:

comuns = ['x', 'c']

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 turn your list into a set (set(minha_lista)). But for in this case it’s also to allow us to use the function intersection (&), as I do below. To declare a set syntactically is like doing with a dictionary but without assigning values to keys (meu_set = {1,2,3}). Using sets in this type of operations is significantly faster than doing them directly in lists or dicts.

Note that the last two examples is to understand the logic, do not use in real projects, exactly for being more expensive, slow, especially in large amounts of data.

Do so:

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

Or:

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

'Manually' would also with normal structures (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 compreension would be (not recommend):

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

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

    Yes - but use the sets sets is much more efficient, especially for large lists - the answer is quite correct, ma sachoque you could add something about the sets: what they are, how they function how they differ from lists, in addition to giving the ready answer.

  • 2

    I’ll do it @jsbueno

Browser other questions tagged

You are not signed in. Login or sign up in order to post.