23

I want to essentially use one list ie.

L = [10, 10, 100, 10, 17, 15]

and using another list

R = [10, 15] 

want to return

N = [0, 1, 3, 5] // indices of L that return the values in R

I tried using L.index() to get the indices but that only returns the first value. I then tried running a for loop over L and using L.index(R[0]) every time, but similarly that only returns the first indices it finds at.

 for i in range(len(L)):
       j = R[i]
       N.append(L.index(j))
 return N

This would return index out of range which makes sense, but how do I get it to run through the L?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Andre Fu
  • 400
  • 1
  • 4
  • 16
  • 4
    Possible duplicate of [How to find all occurrences of an element in a list?](https://stackoverflow.com/questions/6294179/how-to-find-all-occurrences-of-an-element-in-a-list) – Aran-Fey Feb 21 '18 at 04:47
  • https://stackoverflow.com/questions/16685384/finding-the-indices-of-matching-elements-in-list-in-python – juanpa.arrivillaga Feb 21 '18 at 04:47
  • Replace the `if x == "whatever"` part with `if x in R`. You can improve the efficiency if you convert `R` to a set first `R = set(R)`. – Aran-Fey Feb 21 '18 at 04:48
  • 1
    @Aran-Fey yeah nearly, but they only similarly account for only checking one value ie L.index(#) at a time can't pass a L in. Got it below, thanks! – Andre Fu Feb 21 '18 at 05:10

3 Answers3

26
N = []

for i in range(len(L)):

    if L[i] in R:
        N.append(i)

or with a generator

N = [i for i in range(len(L)) if L[i] in R]

or with arrays

import numpy as np

N=np.where(np.isin(L,R))
Demetri Pananos
  • 6,770
  • 9
  • 42
  • 73
1
[i for i,l in enumerate(L) if l in R]
Angelos
  • 185
  • 2
  • 10
0
N = []  
for i, num in enumerate(L):  
    if num in R:  
        N.append(i)