Reputation: 11
I want to compare two lists (list a and list b).
For example:
list a = [a1, a2, a3, a4, a5]
list b = [b1, b2, b3, b4, b5]
if we have...
a1 == b1
a2 == b2
a3 == b3
a4 == b4
a5 == b5
Result: 5
Other example:
list 1 = [1, 2, 3, 4, 5]
list 2 = [1, 7, 9, 4, 5]
Result: 3
Can anybody suggest how to do this in python?
Upvotes: 1
Views: 77
Reputation: 16081
You can do a different approach. If both numbers equal then both are substrated the value will be zero. So, we can count the value of zero.
NB: This approach will only work for numbers.
In [13]: list(map(int.__sub__, list1, list2)).count(0)
Out[13]: 3
Upvotes: 0
Reputation: 1855
You can use a generator expression.
list1 = [1, 2, 3, 4, 5]
list2 = [1, 7, 9, 4, 5]
num_equal = sum(i == j for i, j in zip(list1, list2))
print(num_equal) # 3
zip(list1, list2)
returns an iterator containing tuples of each value in list1
and list2
, essentially forming pairs of corresponding items from the two lists:
print(list(zip(list1, list2))) # [(1, 1), (2, 7), (3, 9), (4, 4), (5, 5)]
You can then check if each pair is equal or not in a list comprehension, creating a list of True
or False
:
print([i == j for i, j in zip(list1, list2)]) # [True, False, False, True, True]
You can take the sum
of this list, as True
casts to the integer 1
and False
casts to the integer 0
. Note that we can use a generator expression instead of a list comprehension (leave out the []
) in the sum
call to be more memory-efficient.
Upvotes: 5
Reputation: 1005
Just loop over both lists and check if the values are the same:
list1 = [1, 2, 3, 4, 5]
list2 = [1, 7, 9, 4, 5]
same = 0
for i in range(len(list1)): # assuming the lists are the same length
if list1[i] == list2[i]:
same += 1
print(same)
Output: 3
Upvotes: 0