Best way to compare a list?

Jeff Epler jepler at unpythonic.net
Wed Jan 28 16:05:30 EST 2004


What do you mean by a "difference"?  For instance, what are the
differences between these two lists:

[1, 2, 3]
[3, 2, 1]

For some purposes you might want to consider them equivalent, since they
both contain 1, 2 and 3 (one time each) and they contain no other
elements.  Or you might want to say that they differ at element 0 and
at element 2.

And for this list, what are the differences?

[1, 3, 4]
[1, 2, 3, 4]

For some purposes, you might say that they differ at indexes 1, 2, and
3.  For other purposes, you might want to say that the second list has
an extra "2" inserted at position 1, but the lists are otherwise the
same.

Once you define what you mean by "differences", perhaps we can be more
helpful.  But once you define exactly what your problem is, the
algorithm to solve it should be more apparent to you, too!

An answer to the simplest of the questions you may have been asking is
this:
    [a == b for a, b in zip(l1, l2)]
this returns a list with True in the positions where corresponding
elements of l1 and l2 are equal, and False elsewhere.

Jeff




More information about the Python-list mailing list