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]
which led me to believe that you can't use else in a list comprehension. However, it seems that you can, but it has to be written differently. This works:
[num if num != 11 else 22 for num in hand]
Why does the if
need to be placed earlier in the comprehension if you use else
with it?
1 answer
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