20

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

user1342516
  • 447
  • 2
  • 5
  • 10
  • possible duplicate of [Python: How to find list intersection?](http://stackoverflow.com/questions/3697432/python-how-to-find-list-intersection) – ChristopheD Apr 28 '12 at 20:03
  • 5
    I don't think this question is a duplicate of that one even though it may be similar. – jamylak Apr 28 '12 at 20:06

4 Answers4

28

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]
jamylak
  • 128,818
  • 30
  • 231
  • 230
  • Thanks a lot! What about this case: 'a = [1, 2, 9, 8]' and 'b = [1, 9, 1]' (b is a subset of a) where the desired result is '[0, 2, 0]' (the indices of a matching each value in b)? Making b a set will lose the index of the second '1' as well as the sequence of the indices. – user1342516 Apr 30 '12 at 14:01
  • In that case wouldn't it be `[0, 2, 0, 1, 2]` or something similar? (since all the items of `b` occur in both lists) – jamylak Apr 30 '12 at 14:14
  • I haven't been clear... The resulting `indices` I need in this case will give `array(a)[indices] = b`. I've edited the question. maybe the description there is clearer. – user1342516 Apr 30 '12 at 14:25
  • You should open your second case up as a new question as nobody will see it here. – jamylak Apr 30 '12 at 14:27
6
def return_indices_of_a(a, b):
  b_set = set(b)
  return [i for i, v in enumerate(a) if v in b_set]
pts
  • 80,836
  • 20
  • 110
  • 183
3

For larger lists this may be of help:

for item in a:
index.append(bisect.bisect(b,item))
    idx = np.unique(index).tolist()

Be sure to import numpy.

0

you can do it like this,with no need to set :

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

inspired by @jamylak

Ahmad Akel Omar
  • 317
  • 2
  • 11