0

How do I extract the number of the same elements between two lists? Most of the answers I've searched for usually are related to finding common elements using set operation, but I'm looking for something like this:

list1 = [1, 2, 3, 4, 5, 6, 7, 8]
list2 = [1, 2, 3, 0, 0, 0, 0, 0]

The elements 1, 2, and 3 are the same, and so we return 3.

I understand that I could simply make a loop and increment a counter, but I'm wondering if there's any method that's more concise or efficient. Thanks in advance.

Sean
  • 2,890
  • 8
  • 36
  • 78

2 Answers2

1

Try this:

print (sum(list1[i] == list2[i] for i in range(min(len(list1), len(list2)))))

Example

>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list2 = [1, 2, 3, 0, 0, 0, 0, 0]
>>> print (sum(list1[i] == list2[i] for i in range(min(len(list1), len(list2)))))
3
smac89
  • 39,374
  • 15
  • 132
  • 179
1

This works for me:

>>> list1 = [1, 2, 3, 4, 5, 6, 7, 8]
>>> list2 = [1, 2, 3, 0, 0, 0, 0, 0]
>>> sum( 1 for a,b in zip(list1,list2) if a == b )
3

Instead of sum() you may use len() -- same result.

lenik
  • 23,228
  • 4
  • 34
  • 43