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.
Post History
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, highlightin...
#3: Post edited
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?
- 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`?
#1: Initial revision
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?