Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count duplicates between 2 lists

Tags:

python

loops

list

a = [1, 2, 9, 5, 1]
b = [9, 8, 7, 6, 5]

I want to count the number of duplicates between the two lists. So using the above, I want to return a count of 2 because 9 and 5 are common to both lists.

I tried something like this but it didn't quite work.

def filter_(x, y):
    count = 0
    for num in y:
        if num in x:
            count += 1
            return count
like image 854
super9 Avatar asked Jan 23 '11 16:01

super9


1 Answers

Shorter way and better:

>>> a = [1, 2, 9, 5, 1]
>>> b = [9, 8, 7, 6, 5]
>>> len(set(a) & set(b))     # & is intersection - elements common to both
2 

Why your code doesn't work:

>>> def filter_(x, y):
...     count = 0
...     for num in y:
...             if num in x:
...                     count += 1
...     return count
... 
>>> filter_(a, b)
2

Your return count was inside the for loop and it returned without execution being complete.

like image 64
user225312 Avatar answered Oct 20 '22 05:10

user225312