I want to compare two lists of same length
a = [1, 3, 5, 7, 9]
b = [1, 2, 5, 7, 3]
and find out the number of differences n
, in this case it'll be n = 2
, and also return an error if the length are not equal. What's the pythonic way of doing this?
The simplest way to do this is to use the sum()
built-in and a generator expression:
def differences(a, b):
if len(a) != len(b):
raise ValueError("Lists of different length.")
return sum(i != j for i, j in zip(a, b))
We loop over the lists together using zip()
and then compare them. As True == 1
and False == 0
, we just sum this to get the number of differences. Another option would be to use the conditional part of the generator expression:
sum(1 for i, j in zip(a, b) if i != j)
I can't really say I feel one is more readable than the other, and doubt there will be a performance difference.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With