Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

list

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?

like image 638
LWZ Avatar asked Feb 16 '13 20:02

LWZ


1 Answers

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.

like image 59
Gareth Latty Avatar answered Oct 14 '22 08:10

Gareth Latty