Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
Why are list comprehensions written differently if you use `else`?
The following list comprehension worked when I tried it:
[num for num in hand if num != 11]
But this doesn't work:
[num for num in hand if num != 11 else 22]
It gives a SyntaxError
, highlighting the else
.
This led me to believe that you can't use else in a list comprehension. However, I then discovered that this is possible instead:
[num if num != 11 else 22 for num in hand]
Why does the if
need to be placed earlier in the comprehension in order to include a matching else
?
2 answers
The following users marked this post as Works for me:
User | Comment | Date |
---|---|---|
true_blue | (no comment) | Nov 19, 2021 at 13:14 |
It's not a matter of order; Python simply does not directly allow else
clauses as part of list comprehensions (docs). When we use
[num if num != 11 else 22 for num in hand]
We are actually using Python's version of the ternary operator; the if
and else
are not part of the list comprehension itself but of the comprehension expression. That is, the above is actually
[(num if num != 11 else 22) for num in hand]
These two uses of if
are different
The if
at the end of a list comprehension syntax:
[num for num in hand if num != 11]
is a filter; its purpose is to decide whether or not the resulting list should contain a value that corresponds to any given num
(for
each one found in hand
).
This is part of the list comprehension syntax. It cannot have a corresponding else
, because that doesn't make logical sense: the purpose is to exclude elements when the condition isn't met, so specifying an alternate value wouldn't be meaningful.
The if
in the working if-else example:
[num if num != 11 else 22 for num in hand]
is part of a conditional expression num if num != 11 else 22
; it is not part of the list comprehension syntax, and it independent meaning. This expression evaluates to num
when num != 11
, and to 22
otherwise (i.e., when num == 11
).
Such an expression must contain an else
part, because it's part of the syntax. It's a conditional expression - not a condition that controls execution of the prior code. Python doesn't have a "void type", and Python expressions must evaluate to some value (or raise an exception) regardless of the input; so a resulting value needs to be specified for both cases of the conditional.
0 comment threads