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.
Comments on Why are list comprehensions written differently if you use `else`?
Parent
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
?
Post
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