Reputation: 12348
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?
Upvotes: 12
Views: 9993
Reputation: 5219
One-liner solution that also produces an error if the length is not equal:
>>> sum(map(lambda x,y: bool(x-y),a,b))
2
Now try the input of different length:
>>> sum(map(lambda x,y: bool(x-y),[1,2],[1]))
TypeError
How it works: bool(x,y) returns True if elements are different. Then we map this function on 2 lists and get the list [False, True, False, True, False].
If we put into the function map() the lists of different length, we get the TypeError
Finally, the function sum() of this boolean list gives 2.
Upvotes: 1
Reputation: 89077
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.
Upvotes: 21
Reputation: 132
You could use sets. Cast both to a set, then find difference between the two. For example:
>>> a = [1,3,5,7,9]
>>> b = [1,2,5,7,2]
>>> len(set(a) - set(b))
2
This could be wrapped up in a function to check for length differences first.
Upvotes: -2