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 vote

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]