Find mismatch item on same index in two list in Python


Sometimes we may need to compare elements in two python lists in terms of both their value and position or index. In this article we will see how to find out the elements in two lists at the same position which do not match in their value.

Using for loop

we can design for loop to compare the values at similar indexes. Id the values do not match then we add the index to a result list. The for loop first fetches the value in the first index and then uses an if condition to compare it with values from the second list.

Example

 Live Demo

listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']

# index variable
idx = 0

# Result list
res = []

# With iteration
for i in listA:
   if i != listB[idx]:
      res.append(idx)
   idx = idx + 1

# Result
print("The index positions with mismatched values:\n",res)

Output

Running the above code gives us the following result −

The index positions with mismatched values:
[0, 3]

With zip

The zip function helps us to write a shorter code as we compare the elements from each index. The index values are captured for positions where the element’s value do not match.

Example

 Live Demo

listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']

res = [listB.index(n) for m, n in
      zip(listA, listB) if n != m]

# Result
print("The index positions with mismatched values:\n",res)

Output

Running the above code gives us the following result −

The index positions with mismatched values:
[0, 3]

With enumerate

It is similar to the approach in zip function except that here we have for loop to go through each element and index when applying enumerate function to one of the list.

Example

 Live Demo

listA= [13, 'Mon',23, 62,'Sun']
listB = [5, 'Mon',23, 6,'Sun']

res = [idx for idx, elem in enumerate(listB)
                           if elem != listA[idx]]

# Result
print("The index positions with mismatched values:\n",res)

Output

Running the above code gives us the following result −

The index positions with mismatched values:
[0, 3]

Updated on: 26-Aug-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements