Python – Filter unequal elements of two lists corresponding same index

Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are unequal and have similar index. This kind of problem can come in many domains. Let’s discuss certain ways in which this problem can be solved.

Method #1 : Using loop + zip()
The combination of above functions can be used to solve this problem. In this, we extract combine the index elements using zip and then extract and check for dissimilarity using conditional statement in loop.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Unequal Equi-index elements
# using loop + zip()
  
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Unequal Equi-index elements
# using loop + zip()
res = []
for i, j in zip(test_list1, test_list2):
    if i != j:
        res.append(i)
  
# printing result
print("Unequal index elements in lists : " + str(res))

chevron_right


Output :



The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Unequal index elements in lists : ['a', 'c']

 

Method #2 : Using zip() + list comprehension
Combination of these functionalities can also be used to solve this problem. In this, we use similar method as above, just a shorthand logic compressed using list comprehension.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 code to demonstrate working of
# Unequal Equi-index elements
# using list comprehension + zip()
  
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
  
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
  
# Unequal Equi-index elements
# using list comprehension + zip()
res = [i for i, j in zip(test_list1, test_list2) if i != j]
  
# printing result
print("Unequal index elements in lists : " + str(res))

chevron_right


Output :

The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Unequal index elements in lists : ['a', 'c']



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.