In Python, find out the number of differences between two ordered lists

I want to compare two lists of the 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 will be n = 2 , and also return an error if the length is not equal. What is the pythonic way to do this?

+7
source share
3 answers

The easiest way to do this is to use the built-in sum() and 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 iterate over the lists together using zip() and then compare them. Like True == 1 and False == 0 , we just sum it up to get the number of differences. Another option is to use the conditional part of the generator expression:

 sum(1 for i, j in zip(a, b) if i != j) 

I can’t say that I feel that one of them is more readable than the other, and I doubt that there will be a difference in performance.

+16
source

A one-line solution that also throws an error if the length is not equal:

 >>> sum(map(lambda x,y: bool(xy),a,b)) 2 

Now try entering a different length:

 >>> sum(map(lambda x,y: bool(xy),[1,2],[1])) TypeError 

How it works: bool (x, y) returns True if the elements are different. Then we map this function to 2 lists and get the list [False, True, False, True, False].
If we enter lists of different lengths into the list of functions (), we get a TypeError

Finally, the sum () function of this Boolean list gives 2.

+1
source

You can use sets . Throw both into a set, then find the 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 can be wrapped in a function to first check for differences in length.

-one
source

All Articles