Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to compare two lists and print out the differences

I have two lists which are guaranteed to be the same length. I want to compare the corresponding values in the list (except the first item) and print out the ones which dont match. The way I am doing it is like this

i = len(list1)
if i == 1:
    print 'Nothing to compare'
else:
    for i in range(i):
        if not (i == 0):
            if list1[i] != list2[i]:
                print list1[i]
                print list2[i]

Is there a better way to do this? (Python 2.x)

like image 981
randomThought Avatar asked Mar 05 '10 15:03

randomThought


People also ask

How do I compare two lists and differences in Python?

The difference between two lists (say list1 and list2) can be found using the following simple function. By Using the above function, the difference can be found using diff(temp2, temp1) or diff(temp1, temp2) . Both will give the result ['Four', 'Three'] .

How do you find the difference between two lists?

Use set() to find the difference of two lists In this approach, we'll first derive two SETs (say set1 and set2) from the LISTs (say list1 and list2) by passing them to set() function. After that, we'll perform the set difference operation. It will return those elements from list1 which don't exist in the second.

How do you compare two lists in Python?

Using list.sort() method sorts the two lists and the == operator compares the two lists item by item which means they have equal data items at equal positions. This checks if the list contains equal data item values but it does not take into account the order of elements in the list.

How do you find the absolute difference between two lists in Python?

Method 6: Use symmetric_difference to Find the Difference Between Two Lists in Python. The elements that are either in the first set or the second set are returned using the symmetric_difference() technique. The intersection, unlike the shared items of the two sets, is not returned by this technique.


2 Answers

list1=[1,2,3,4]
list2=[1,5,3,4]
print [(i,j) for i,j in zip(list1,list2) if i!=j]

Output:

[(2, 5)]

Edit: Easily extended to skip n first items (same output):

list1=[1,2,3,4]
list2=[2,5,3,4]
print [(i,j) for i,j in zip(list1,list2)[1:] if i!=j]
like image 164
Mizipzor Avatar answered Oct 04 '22 18:10

Mizipzor


Nobody's mentioned filter:

a = [1, 2, 3]
b = [42, 3, 4]

aToCompare = a[1:]
bToCompare = b[1:]

c = filter( lambda x: (not(x in aToCompare)), bToCompare)
print c
like image 42
RyanWilcox Avatar answered Oct 04 '22 17:10

RyanWilcox