To Find the index of multiple elements in the Python list creates a dictionary containing the index location of each item in the list. Then use the dictionary to look up each item’s index location which is average time complexity O(1).
Find the index of multiple elements in the list Python example
A simple example code finds the index for multiple elements in a long list.
my_list = ['ab', 'sd', 'ef', 'de']
d = {item: idx for idx, item in enumerate(my_list)}
items_to_find = ['sd', 'ef', 'sd']
res = [d.get(item) for item in items_to_find]
print(res)
Output:
Use of the for Loop to Find the Indices of All the Occurrences of an Element.
l1 = [1, 5, 1, 8, 9, 15, 6, 2, 1]
pos = []
x = 1
for i in range(len(l1)):
if l1[i] == x:
pos.append(i)
print(pos)
Output: [0, 2, 8]
Comment if you have any doubts or suggestions on this Python list topic.
Note: IDE: PyCharm 2021.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.