Python get list of indices of elements of one list of another list
- User
Python get list of indices of elements of one list of another list
- Assistant
Python get list of indices of elements of one list of another list
To get a list of indices where elements from one list (list1) occur in another list (list2) in Python, you can use list comprehensions along with the enumerate() function. Below are several methods to achieve this, depending on your specific needs.
list1 Occur in list2If you want a flat list of all indices in list2 where any element from list1 occurs, you can use:
list1 = ['apple', 'banana', 'cherry']
list2 = ['banana', 'cherry', 'durian', 'apple', 'banana', 'cherry']
indices = [i for i, x in enumerate(list2) if x in list1]
print(indices)
Output:
[0, 1, 3, 4, 5]
This code goes through list2 and checks if each element is in list1. If it is, it records the index.
list1 to Its Indices in list2If you want to know the indices for each specific element from list1 in list2, you can create a dictionary:
list1 = ['apple', 'banana', 'cherry']
list2 = ['banana', 'cherry', 'durian', 'apple', 'banana', 'cherry']
indices_dict = {item: [i for i, x in enumerate(list2) if x == item] for item in list1}
print(indices_dict)
Output:
{'apple': [3], 'banana': [0, 4], 'cherry': [1, 5]}
This dictionary maps each element from list1 to a list of all indices where it occurs in list2.
list1 in list2If you're interested only in the first occurrence of each element from list1 in list2, you can use:
list1 = ['apple', 'banana', 'cherry']
list2 = ['banana', 'cherry', 'durian', 'apple', 'banana', 'cherry']
indices = [list2.index(item) if item in list2 else -1 for item in list1]
print(indices)
Output:
[3, 0, 1]
This will return the index of the first occurrence of each element. If an element from list1 is not found in list2, it returns -1.
Note: Using list.index() can be inefficient for large lists because it searches through the list every time. If performance is a concern, consider using a different method.
For better performance with large lists, you can create a mapping from elements to their indices once:
from collections import defaultdict
list1 = ['apple', 'banana', 'cherry']
list2 = ['banana', 'cherry', 'durian', 'apple', 'banana', 'cherry']
index_lookup = defaultdict(list)
for index, value in enumerate(list2):
index_lookup[value].append(index)
indices_dict = {item: index_lookup[item] for item in list1 if item in index_lookup}
print(indices_dict)
Output:
{'apple': [3], 'banana': [0, 4], 'cherry': [1, 5]}
This method builds a lookup table (index_lookup) that maps each element in list2 to a list of indices where it occurs. This is more efficient if you need to perform multiple lookups.
If list1 may contain duplicates and you want indices in list2 corresponding to each occurrence, preserving the order, you can use:
list1 = ['banana', 'apple', 'banana']
list2 = ['banana', 'cherry', 'durian', 'apple', 'banana', 'cherry']
indices = []
index_tracker = {item: 0 for item in set(list1)}
for item in list1:
count = index_tracker[item]
try:
# Find the index of the nth occurrence
idx = [i for i, x in enumerate(list2) if x == item][count]
indices.append(idx)
index_tracker[item] += 1
except IndexError:
# If the nth occurrence doesn't exist
indices.append(-1)
print(indices)
Output:
[0, 3, 4]
This code tracks how many times each item has been found and searches for the next occurrence in list2.
If your lists contain numerical data and you have NumPy installed, you can use:
import numpy as np
list1 = [2, 4, 6]
list2 = [1, 2, 3, 4, 5, 6]
list2_np = np.array(list2)
indices = [np.where(list2_np == item)[0].tolist() for item in list1]
print(indices)
Output:
[[1], [3], [5]]
NumPy's where function efficiently finds indices in numerical arrays.
Choose the method that best fits your use case based on the size of your lists and whether you're working with numerical data or not.
Not yet included in a published release.