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
                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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With