Search code examples
pythonlist-comprehension

Can someone explain implicit "for loops" to me?


I am very sorry, I do not understand implicit for loops. So I thought I could ask whether someone will explain this a bit more for me.

I have - under great pains - written the following implicit for loop:

ueberdata= [1,5,2,6,1,2,3,4,1,3,5,6]
order = [1,3,5]
ind = [list(ueberdata).index(i) for i in order]

this gives me the indices of the first occurrences of the stuff in order.

ind : 0,6,2

So far so fine. Now I want to expand this example. Maybe ueberdata is bigger. Maybe I would now like to have ALL the indices. And I am stumped. I have to nest these for loops somehow. Can someone help me understand this good enough to solve this problem?

Some clarification (sorry guys, i really need to express myself better): What i essentially want to do is plot a dataset. I have these 3 types of datapoints i want to see on my plot. Now my dataset is of course longer than 3 :). And I want to plot another column, so I need those indices. Sorry for telling that just now, but I thought it might distract from my question. I want to plot all datapoints in my file, not just the first set.


Solution

  • That's called a "list comprehension".

    Your code could be made simpler, not sure why you're re-creating the list when you already have it:

    ind = [uberdata.index(i) for i in order]
    

    If you want more indices, just make order longer.