15

My list has

a = [1,2,3,4,2,7,3,5,6,7]
b = [1,2,3,1,2,5,6,2,6,7]

I need to count if a[i]==b[i].

For the above example, the answer should be

6

Detail description of answer is

a[0]==b[0] (1==1)
a[1]==b[1] (2==2)
a[2]==b[0] (3==3)
a[4]==b[4] (2==2)
a[8]==b[8] (6==6)
a[9]==b[9] (7==7)
1
  • I need to count how many identical values(a[i]==b[i]) are in the lists. I got the answer from below. thanks for asking.
    – Krush23
    Jul 22, 2019 at 11:16

6 Answers 6

32

In a one-liner:

sum(x == y for x, y in zip(a, b))
1
  • 12
    sum(1 for x, y in zip(a, b) if x == y) can be quite a lot faster, depending on how often the comparison is False, as I also recently discovered.
    – Graipher
    Jul 22, 2019 at 21:24
15

One way would be to map both lists with operator.eq and take the sum of the result:

from operator import eq

a = [1,2,3,4,2,7,3,5,6,7]
b = [1,2,3,1,2,5,6,2,6,7]

sum(map(eq, a, b))
# 6

Where by mapping the eq operator we get either True or False depending on whether items with the same index are the same:

list(map(eq, a, b))
# [True, True, True, False, True, False, False, False, True, True]
7

You can use some of Python's special features:

sum(i1 == i2 for i1, i2 in zip(a, b))

This will

  • pair the list items with zip()
  • use a generator expression to iterate over the paired items
  • expand the item pairs into two variables
  • compare the variables, which results in a boolean that is also usable as 0 and 1
  • add up the 1s with sum()
1
  • I prefer your method to mine. Thanks.
    – Deepstop
    Jul 22, 2019 at 11:10
1

Using a generator expression, take advantage of A == A is equal to 1 and A != A is equal to zero.

a = [1,2,3,4,2,7,3,5,6,7]
b = [1,2,3,1,2,5,6,2,6,7]
count = sum(a[i] == b[i] for i in range(len(a)))
print(count)

6
1
1

Using numpy:

import numpy as np
np.sum(np.array(a) == np.array(b))
0

A little similar to @yatu's solution, but I save an import, I use int.__eq__:

print(sum(map(int.__eq__, a, b)))

Output:

6
2
  • or just with some lovely lambda sum(map(lambda x,y : x==y, a, b))
    – Daria
    Jul 30, 2019 at 10:33
  • @Daria lambda isn't lovely nor efficient here Jul 31, 2019 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.