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
Get match indices in Python
When working with two lists in Python, you often need to find the indices of elements in the first list that match values in the second list. Python provides several approaches to accomplish this task efficiently.
Using index() Method
The simplest approach uses list comprehension with the index() method to find the position of each matching element ?
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
target_days = ['Tue', 'Fri']
# Given lists
print("The given list:", days)
print("The list of values:", target_days)
# Using index() method
match_indices = [days.index(item) for item in target_days]
# Result
print("The match indices list is:", match_indices)
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The match indices list is: [1, 4]
Using enumerate() with Set Lookup
This method uses enumerate() to get both index and value, then checks membership using a set for faster lookup ?
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
target_days = ['Tue', 'Fri']
# Given lists
print("The given list:", days)
print("The list of values:", target_days)
# Using enumerate with set lookup
match_indices = [index for index, value in enumerate(days)
if value in set(target_days)]
# Result
print("The match indices list is:", match_indices)
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The match indices list is: [1, 4]
Using NumPy for Large Lists
For large datasets, NumPy provides more efficient operations ?
import numpy as np
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri']
target_days = ['Tue', 'Fri']
# Convert to numpy arrays
arr1 = np.array(days)
arr2 = np.array(target_days)
# Find indices using numpy
match_indices = [np.where(arr1 == item)[0][0] for item in arr2]
print("The given list:", days)
print("The list of values:", target_days)
print("The match indices list is:", match_indices)
The given list: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'] The list of values: ['Tue', 'Fri'] The match indices list is: [1, 4]
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
index() |
O(n×m) | Small lists, simple cases |
enumerate() + set |
O(n+m) | Medium lists, multiple lookups |
NumPy |
O(n×m) | Large datasets, numerical data |
Conclusion
Use index() for simple cases with small lists. For better performance with larger lists or multiple lookups, use enumerate() with set conversion. NumPy is ideal for numerical data and very large datasets.
