+4 votes
in Programming Languages by (40.5k points)

The list index() method is extremely slow when I try to find the indices of 1000s of elements in a big list. Is there any function or quick method to find the indices?

E.g.

a= [10,20,30...1000]

b=[1....100,000]

The index() method takes several seconds to find indices of elements of 'a' in 'b'. Both lists have unique elements.

1 Answer

+2 votes
by (348k points)
selected by
 
Best answer

Yes, if you use the index() method to find indices of a large number of elements in a big list, it may take minutes to finish.

You can create a dictionary with elements of the big list as keys and their indices as values. Finding indices using a dictionary will be extremely fast.

Here is an example.

>>> a=[10,20,30,40,50,60,70,80,90,100]
>>> b=[40,70,30,20]
>>> a_dict = dict(zip(a, range(len(a))))
>>> a_dict
{10: 0, 20: 1, 30: 2, 40: 3, 50: 4, 60: 5, 70: 6, 80: 7, 90: 8, 100: 9}
>>> idx = [a_dict[v] for v in b]
>>> idx
[3, 6, 2, 1]
 


...