Question

Let L = [1, 2, 3, 1, 1, 5]. Do you know why this works in Python :

for idx in [idx for idx, item in enumerate(L) if item == 1]:
   dosomething(idx)      # idx = 0, 3, 4 

but this doesn't :

for idx, item in enumerate(L) if item == 1:
   dosomething(idx)

?

Was it helpful?

Solution

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.

for-if without list comprehension in one line

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top