Python | Retrieve Similar Index Items

Python Methods and Functions

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

# Python3 code to demonstrate how it works
# Extract similar index items
# using loop + zip ()

 
# initialize lists

test_list1 = [ "a" , "b" , "c" , "d" ]

test_list2 = [ " g " , " b " , "s" , " d " ]

  
# print original lists

print ( "The original list 1:" + str (test_list1))

print ( "The original list 2: " + str (test_list2))

 
# Retrieve similar index items
# using loop + zip ()

res = []

for i, j in zip (test_list1, test_list2):

if i = = j:

res.append ( i)

 
# print result

print ( "Similar index elements in lists:" + str (res))

Output:

 The original l ist 1: [`a`,` b`, `c`,` d`] The original list 2: [`g`,` b`, `s`,` d`] Similar index elements in lists: [` b`, `d`] 

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

# Python3 code to demonstrate how it works
# Extract similar index items
# using a 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))

 
# Retrieve similar index items
# using understanding list + zip ()

res = [i for i, j in zip (test_list1, test_list2) if i = = j]

 
# print result

print ( "Similar index elements in lists:" + str (res))

Output:

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




Get Solution for free from DataCamp guru