1

I have 2 lists

lst = [1,2,3,4,5,1,2,1,2,3]
lst2 = [1,2,3]

I am trying to see the index elements in lst are in lst2. Currently I am doing;

ind = []
for x in lst2:
    if x in lst:
        ind.append(lst.index(x))

I realize the problem is that lst.index(x) only returns the first occurrence of the element so x=1 will always return lst.index(1) = 0.

Is there a way to return all the indexes that contain the element?

Ahmed
  • 292
  • 1
  • 7
  • 15
  • These kind of operation look like they want to be implemented with sets. What the actual purpose of finding the index? – Klaus D. Jun 16 '17 at 16:29
  • I have predicted data and observed data, stored in DataFrames. I need those indexes to find when the dates are the same in both indexes so I can compare several different filed. – Ahmed Jun 16 '17 at 16:39

2 Answers2

5

You might use something like

ind = [[i for i, value in enumerate(lst) if value == x] for x in lst2]

I don't know a purpose of this operation, but it might be more useful to use dict comprehension:

ind = {x: [i for i, value in enumerate(lst) if value == x] for x in lst2}

because in this case you will have output like that: {1: [0, 5, 7], 2: [1, 6, 8], 3: [2, 9]}, which might be easier to use.

Vlad Sydorenko
  • 601
  • 4
  • 6
1

This does what you asked for:

ind = [i for i, x in enumerate(lst) for y in lst2 if x == y]
zipa
  • 27,316
  • 6
  • 40
  • 58