Common elements between lists

0

How do I compare elements of 2 lists, and return the quantity of elements in common? For example:

a=[1, 2, 3, 4, 5]
b=[6, 7, 8, 9, 10, 1, 2, 11, 22]

This should return 2, because there are only 2 elements in common.

    
asked by anonymous 22.11.2017 / 18:45

2 answers

2

Just intersect the two lists and then see the number of elements.

comum=len(set(a).intersection(b))
    
22.11.2017 / 19:08
2

Set a num_repeat variable with value 0 that will serve as counter:
>>> num_repetido = 0

Loop the list by checking if any of the numbers are repeated and then add the variable num_repetido:

 for num in a:
  if num in b:
   num_repetido += 1

And finally print the final value of the num_repeat variable on the screen: >>> print(num_repetido)

It's worth pointing out that there are several ways to do this, as the friend above put it all depends on what you need. Thanks.

    
22.11.2017 / 19:27