Open In App

Python - Get match indices

Last Updated : 20 Dec, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Getting match indices in Python involves identifying the positions of specific substrings or patterns within a string. It helps in locating where a certain sequence occurs, facilitating further operations based on those positions. In this article, we will see How to match indices in a list.

Using Dictionary

Dictionary quickly finds the index of elements from one list in another. It allows for quick lookups, making it an efficient choice for matching indices between two lists. The dictionary maps each element of one list to its index.

Example:

Python
a = [5, 4, 1, 3, 2]
b = [1, 2]

# map element to their indices
d= {value: idx for idx, value in enumerate(a)}

# get indices
i = [d[i] for i in b]  
print( i)

Output
[2, 4]

Explanation:

  • This code creates dictionary d that maps each element of list a to its index.
  • It then retrieves the indices of elements in list b by looking them up in the dictionary d.

Let's discuss more methods to match indices in Python.

Using Set

By converting one list to a set, we can quickly check if its elements are present ina another list.

Example:

Python
a = [5, 4, 1, 3, 2]
b = [1, 2]

 # convert b to set
s = set(b) 

# get indices using enumerate and set lookup
i = [idx for idx, value in enumerate(a) if value in s]  
print(i) 

Output
[2, 4]

Explanation:

  • List b is converted to set for fast membership testing.
  • Indices of elements in a that are in b are collected.

Using enumerate()

enumerate function can be used to produce the key value pair for the list being it's index and value and we can store them using list comprehension. 

Example:

Python
a = [5, 4, 1, 3, 2]
b = [1, 2]

# get indices using enumerate
i = [idx for idx, value in enumerate(a) if value in b] 

print(i)

Output
[2, 4]

Using Index

index() method finds position of each element from list2 in list1 by performing a linear search.

Python
a = [5, 4, 1, 3, 2]
b= [1, 2]

# get indices using index()
i = [a.index(i) for i in b]  
print(i)

Output
[2, 4]

Explanation:

  • index() method to find the position of each element from list b in list a.
  • returns list of indices where each element of b is found in a.

Next Article

Similar Reads