+2 votes
in Programming Languages by (8.1k 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 (15.8k points)

If your lists are small and you don't care about runtime, you can use 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]

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]
...