2

I have two lists of strings. I want to compare all the items in list 1 to list 2 and then count the matches. Here's what I've tried:

count = 0

global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
local_fruit = ['bananas', 'apricots', 'oranges']

if any(f in global_fruit for f in local_fruit):
count += 1

print(count)

This returns a count of 1 because the script exits as soon as it finds the first match in the second list. I want it to return a count of 3 because there are three matches between the lists.

Is there a way to do this? Order is not important.

ipconfuse
  • 37
  • 1
  • 6

3 Answers3

4

You can use sum instead of any and get the result immediately:

global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
local_fruit = ['bananas', 'apricots', 'oranges']

count = sum(f in global_fruit for f in local_fruit)

print(count)

Also, you could convert your lists into sets and find the number of intersections:

global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
global_fruit_set = set(global_fruit)
local_fruit = ['bananas', 'apricots', 'oranges']
local_fruit_set = set(local_fruit)

count = len(global_fruit_set.intersection(local_fruit_set))
print(count)
Pavel Botsman
  • 773
  • 1
  • 11
  • 25
  • Both your answers worked, but the first one was ideal for what I needed. Thanks to you and also the answer from komatiraju032. My account is quite new so you won't see the upvotes but they are there. – ipconfuse May 27 '20 at 14:21
3
global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
local_fruit = ['bananas', 'apricots', 'oranges']
count=0 
for a in global_fruit:
    if(a in local_fruit):
        count+=1
print(count)
  • 2
    Welcome to Stack Overflow. Code dumps without any explanation are rarely helpful. Stack Overflow is about learning, not providing snippets to blindly copy and paste. Please [edit] your question and explain how it works better than what the OP provided. See [answer]. – ChrisGPT was on strike May 28 '20 at 01:10
2

Try this:

global_fruit = ['apples', 'bananas', 'pears', 'oranges', 'peaches', 'apricots', 'mangoes']
local_fruit = ['bananas', 'apricots', 'oranges']

print(len(local_fruit) - len(set(local_fruit) - set(global_fruit)))
deadshot
  • 8,881
  • 4
  • 20
  • 39