+3 votes
in Programming Languages by (73.8k 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

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

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)
>>>


...