compare two lists in python and return indices of matched values

user1342516 picture user1342516 · Apr 28, 2012 · Viewed 30.8k times · Source

For two lists a and b, how can I get the indices of values that appear in both? For example,

a = [1, 2, 3, 4, 5]
b = [9, 7, 6, 5, 1, 0]

return_indices_of_a(a, b)

would return [0,4], with (a[0],a[4]) = (1,5).

Answer

jamylak picture jamylak · Apr 28, 2012

The best way to do this would be to make b a set since you are only checking for membership inside it.

>>> a = [1, 2, 3, 4, 5]
>>> b = set([9, 7, 6, 5, 1, 0])
>>> [i for i, item in enumerate(a) if item in b]
[0, 4]