Get match indices in Python


Two lists are given. We need to find the index of the elements from the first list whose values match with the elements in the second list.

With index

We simply design follow to get the value of the element in the second list and extract the corresponding index from the first list.

Example

 Live Demo

listA = ['Mon','Tue', 'Wed', 'Thu', 'Fri']
listB = ['Tue', 'Fri']
# Given lists
print("The given list:\n ",listA)
print("The list of values:\n ",listB)
# using indices
res = [listA.index(i) for i in listB]
# Result
print("The Match indices list is : ",res)

Output

Running the above code gives us the following result −

The given list:
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The list of values:
['Tue', 'Fri']
The Match indices list is : [1, 4]

With enumerate and set

We will design a for loop which will use enumerate to extract all the elements and then match them with the key value pairs. Finally, it will extract the matching indices.

Example

 Live Demo

listA = ['Mon','Tue', 'Wed', 'Thu', 'Fri']
listB = ['Tue', 'Fri']
# Given lists
print("The given list:\n ",listA)
print("The list of values:\n ",listB)
# using enumerate
res = [key for key, val in enumerate(listA)
if val in set(listB)]
# Result
print("The Match indices list is : ",res)

Output

Running the above code gives us the following result −

The given list:
['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
The list of values:
['Tue', 'Fri']
The Match indices list is : [1, 4]

Updated on: 04-Jun-2020

429 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements