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)
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'] .
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.
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.
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.
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]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With