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
Selected Reading
Python - Filter unequal elements of two lists corresponding same index
When working with two lists in Python, you may need to find elements that are equal at the same index positions. This is useful for data comparison, synchronization, and filtering operations.
For example, given two lists:
list1 = [10, 20, 30, 40, 50] list2 = [1, 20, 3, 40, 50] # Elements at same index: 20, 40, 50 are equal
Using zip() and List Comprehension
The most Pythonic approach uses zip() to pair elements and list comprehension to filter matches ?
list1 = [1, 2, 3, 4, 5]
list2 = [1, 2, 9, 6, 5]
# Find equal elements at same index
result = [x for x, y in zip(list1, list2) if x == y]
print("Equal elements at same index:", result)
Equal elements at same index: [1, 2, 5]
Using enumerate() to Get Indices
When you need both the indices and values of unequal elements ?
list1 = ["abc", "bcd", "c", "d"]
list2 = ["g", "bcd", "s", "d"]
# Get indices where elements are not equal
unequal_indices = [i for i, (val1, val2) in enumerate(zip(list1, list2)) if val1 != val2]
print("Indices with unequal elements:", unequal_indices)
# Get equal elements at same index
equal_elements = [val1 for i, (val1, val2) in enumerate(zip(list1, list2)) if val1 == val2]
print("Equal elements:", equal_elements)
Indices with unequal elements: [0, 2] Equal elements: ['bcd', 'd']
Using filter() and lambda
A functional programming approach using filter() ?
list1 = [11, 2, 3, 4, 5]
list2 = [1, 2, 3, 6, 5]
# Filter equal pairs and extract values
equal_pairs = list(filter(lambda x: x[0] == x[1], zip(list1, list2)))
result = [pair[0] for pair in equal_pairs]
print("Equal elements at same index:", result)
Equal elements at same index: [2, 3, 5]
Using Traditional for Loop
A straightforward approach using a loop ?
list1 = [1, 20, 3, 40, 5]
list2 = [1, 2, 30, 6, 5]
result = []
for i in range(len(list1)):
if list1[i] == list2[i]:
result.append(list1[i])
print("Equal elements at same index:", result)
Equal elements at same index: [1, 5]
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
zip() + list comprehension |
High | Fast | Most cases |
enumerate() |
Medium | Fast | When indices needed |
filter() + lambda |
Medium | Medium | Functional style |
for loop |
High | Slow | Complex logic |
Conclusion
Use zip() with list comprehension for the most efficient and readable solution. Use enumerate() when you need the indices of equal or unequal elements.
Advertisements
