+2 votes
in Programming Languages by (74.2k points)
How to find the indices of common elements in two lists?

E.g. In the following two lists, [3,4] are common in 'a' and 'b'. How to find the indices of [3,4] in lists 'a' and 'b' in pythonic way?

>>> a=[1, 2, 4, 3]
>>> b=[3,4,5,6]

1 Answer

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

You can use function intersect1d() of Numpy with parameter return_indices=True. This function will return the common elements along with their indices in both lists.

>>> a=[1, 2, 4, 3]
>>> b=[3,4,5,6]

>>> ab,a_ind,b_ind=np.intersect1d(a,b, return_indices=True)
>>> ab
array([3, 4])
>>> a_ind
array([3, 2], dtype=int64)
>>> b_ind
array([0, 1], dtype=int64)
 


...