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
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]
0 comment threads