+2 votes
in Programming Languages by (7k points)
I have a list e.g. aa=[1,2,3,4,5,6,7,8,9,10] and a sublist e.g. bb = [2,5,7]. How can I find the indices of all elements of sublist bb in list aa. I do not want to use for loop.

1 Answer

0 votes
by (13.5k points)

You can use isin() function of numpy to find the indices. Have a look at the following example.

>>> aa=[1,2,3,4,5,6,7,8,9,10]
>>> bb = [2,5,7]
>>> import numpy as np
>>> np.isin(aa,bb)
array([False,  True, False, False,  True, False,  True, False, False,
       False])
>>> np.isin(aa,bb).nonzero()[0]
array([1, 4, 6], dtype=int64)
>>>

...