+2 votes
in Programming Languages by (73.2k points)
I have two lists. I want to find the indices of elements present in list1 in list2. Is there any way to get the indices of several elements in a numpy array or list at once?

For example:

c = [1, 2, 3]
f = [ 9, 11,  1, 13,  4,  5,  3, 12, 14, 10,  2,  7,  8,  6]
output should be [2,6,10]

1 Answer

+1 vote
by (346k points)
selected by
 
Best answer

If your lists are small and you don't care about runtime, you can use the index() function as follows:

>>> c = [1, 2, 3]

>>> f = [ 9, 11,  1, 13,  4,  5,  3, 12, 14, 10,  2,  7,  8,  6]

>>> idx = [f.index(i) for i in c]

>>> idx

[2, 10, 6]

If you are not concerned about the sequence of indices in the output, you can use NumPy's in1d and nonzero functions.  in1d tests whether each element of a 1-D array is also present in a second array. A common use of nonzero is to find the indices of an array, where a condition is True. Look at the following example:

>>> import numpy as np

>>> np.in1d(np.array(f),np.array(c)).nonzero()[0]

array([ 2,  6, 10], dtype=int64)

>>> np.in1d(f,c).nonzero()[0]

array([ 2,  6, 10], dtype=int64)

Here, the output is [2,6,10] instead of [2,10,6]


...