Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Find mismatch item on same index in two list in Python
Sometimes we need to compare elements in two Python lists based on both their value and position. This article shows different methods to find indices where elements at the same position have different values.
Using for Loop
We can design a for loop to compare values at similar indexes. If the values do not match, we add the index to a result list ?
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)
The index positions with mismatched values: [0, 3]
Using zip() Function
The zip() function helps us write shorter code by pairing elements from each list. However, there's an issue with the previous approach - it finds the first occurrence index, not the actual position ?
listA = [13, 'Mon', 23, 62, 'Sun']
listB = [5, 'Mon', 23, 6, 'Sun']
# Correct approach using zip with enumerate
res = [idx for idx, (a, b) in enumerate(zip(listA, listB)) if a != b]
# Result
print("The index positions with mismatched values:\n", res)
The index positions with mismatched values: [0, 3]
Using enumerate() Function
This approach uses enumerate() to get both index and element, then compares with the corresponding element in the other list ?
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)
The index positions with mismatched values: [0, 3]
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
| For Loop | Good | Moderate | Beginners |
| zip() + enumerate() | Excellent | Good | Pythonic approach |
| enumerate() | Good | Good | Simple comparison |
Conclusion
Use zip() with enumerate() for the most Pythonic solution. Use enumerate() for simple cases, and basic for loops when learning Python fundamentals.
