You can't have a conditional in your for loop like that, it's a syntax error.
It would have to be inside the loop like so:
for idx, item in enumerate(L):
if item == 1:
dosomething(idx)
Your first example is a list comprehension, and your list comprehension is syntactically sound.
As an aside, you can use an if
and an else
in the same list comprehension, but the syntax changes around a little, like so:
list_comp = [x if *condition* else y for x in z]
More info on list comprehensions here, here and Google ;)
EDIT:
Since this has been accepted as the answer, I will also include here, for completeness, the link that @Kyle Strand
posted in the comments with regards to the actual reasons(under the hood) that the for/if
syntax in your question is invalid.