Search code examples
pythonlistzip

how to find index of mismatch elements in two lists with two elements variants?


I have two different lists with two elements variants: 'POSITIVE' and 'NEGATIVE'. I made a list comprehension to find mismatches, but I can't return the indexes using index(), maybe I'm using the function in the wrong place. I'm trying to accomplish this keeping the list comprehension.

Code

l1 = ['POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE',
           'POSITIVE', 
           'POSITIVE', # mismatch
           'POSITIVE', 
           'POSITIVE'] # mismatch

l2 = ['POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE', 'POSITIVE', 'NEGATIVE',
           'POSITIVE', 
           'NEGATIVE', # mismatch
           'POSITIVE', 
           'NEGATIVE'] # mismatch

mismatch = [i for i, j in zip(l1, l2) if i != j]

print(mismatch)
['POSITIVE', 'POSITIVE']

# expected output
[7, 9]

Solution

  • i and j are iterating over the elements of the lists, not the indices. If you want to get the index, use the enumerate function in python:

    mismatch = [i for i, (a, b) in enumerate(zip(l1, l2)) if a != b]
    

    Here's another way using range instead of enumerate and zip:

    mismatch = [i for i in range(len(l1)) if l1[i] != l2[i]]