Home > OS >  Counting how many items in a list are identical
Counting how many items in a list are identical

Time:12-09

I have two lists of the same size, a and b. I want to get a count for how many items in the list have the same number at the same index. I.e if a = [1,2,3,4] and b = [1,4,5,4] then the returned sum would be 2.

I have tried this :

for i in range(len(a)):
    sum = 0
    if a[i] == b[i]:
        sum =1

CodePudding user response:

Try this:

sum(i==j for i,j in zip(a,b))

CodePudding user response:

For the minimal fix to your code, you need to move the sum initialization out of the loop:

sum = 0
for i in range(len(a)):
    if a[i] == b[i]:
        sum =1

But there's a pretty oneliner in the comments also.

  • Related