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)
yatu
  • 86,083
  • 12
  • 84
  • 139
Krush23
  • 723
  • 7
  • 19
  • 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 '19 at 11:16

6 Answers6

32

In a one-liner:

sum(x == y for x, y in zip(a, b))
martyn
  • 676
  • 7
  • 17
  • 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](https://stackoverflow.com/q/56288015/4042267). – Graipher Jul 22 '19 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]
yatu
  • 86,083
  • 12
  • 84
  • 139
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()
Klaus D.
  • 13,874
  • 5
  • 41
  • 48
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
Deepstop
  • 3,627
  • 2
  • 8
  • 21
1

Using numpy:

import numpy as np
np.sum(np.array(a) == np.array(b))
Ardweaden
  • 857
  • 9
  • 23
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
U13-Forward
  • 69,221
  • 14
  • 89
  • 114