I just stumbled over what seems to be a flaw in the python syntax-- or else I'm missing something.
See this:
[x for x in range(30) if x % 2 == 0]
But this is a syntax error:
[x for x in range(30) if x % 2 == 0 else 5]
If you have an else
clause, you have to write:
[x if x % 2 == 0 else 5 for x in range (30)]
But this is a syntax error:
[x if x %2 == 0 for x in range(30)]
What am I missing? Why is this so inconsistent?
You are mixing syntax here. There are two different concepts at play here:
List comprehension syntax. Here
if
acts as a filter; include a value in the iteration or not. There is noelse
, as that is the 'don't include' case already.A conditional expression. This must always return a value, either the outcome of the 'true' or the 'false' expression.
The following is a ternary operation (aka "conditional expression" in python parlance)
This evaluates like it reads: if
some_boolean
isTrue
, give mex
, else give me y.Do not confuse this with comprehension syntax:
A conditional expression can go into the (expression) part. It doesn't have anything to do with the optional
if (filter)
part.The difference between the two is that the trailing
if
in the first one is part of the list comprehension syntax, while theif-else
is the conditional operator, not any part of the list comprehension syntax - as it is an expression which is permitted in that part of a list comprehension.The syntax for the conditional operator is as follows:
This returns the value of the expression that is evaluated, which is why it seems to "work" for your case, though it evaluates all of the time and returns always - which is the key difference between the two.
Meanwhile, for the list comprehension, it tests whether or not the condition applies, and does not add that in the new list created if the condition does not evaluate to true according to the Truth Value Testing procedure, not
None
nor anything else.Compare the following (taking an example from PEP202):
a
would bewhile
b
would bewhich isn't the same at all, as no matter what the result of it is, it will still add it in if there is no
if
part of the list comprehension.