Elements in common between lists

Asked

Viewed 2,960 times

1

How do I compare elements from 2 lists, and return the amount 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.

  • 1

    Can lists contain duplicate elements? That is, without two numbers 1 in a and b, must be accounted for once or twice?

2 answers

2

Just make the intersection of the two lists and then see the number of elements.

comum=len(set(a).intersection(b))

2

Set a variable on a repeated worthwhile 0 who will serve as an accountant:
>>> num_repetido = 0

Loop the list to see if any of the numbers repeat and then add in the repeated num_variable:

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

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

It is worth noting that there are several ways to do this, as the friend above put it, everything depends on what you need. Hug.

Browser other questions tagged

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