NMA
NMA

Reputation: 35

Counting how many items in a list are identical

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

Upvotes: 0

Views: 120

Answers (2)

vaizki
vaizki

Reputation: 1932

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.

Upvotes: 0

Pedro Maia
Pedro Maia

Reputation: 2732

Try this:

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

Upvotes: 2

Related Questions