On Thu, Oct 05, 2017 at 05:40:32PM +0200, Jason H wrote:
> >>> a = [1,2,3]
> >>> [ x for x in a if x & 1]
> [1, 3]
> >>> [ x for x in a if x & 1 else 'even']
> File "", line 1
> [ x for x in a if x & 1 else 'even']
> ^
> SyntaxError: invalid syntax
[(x if x
Putting it another way, your example doesn't make sense. How would you
parenthesise it to make it clearer?
[ (x for x in a if x & 1) else 'even'] You have an "else"
without an "if".
[ x for x in (a if x & 1 else 'even')] Using x before it has
been defined, at least in this
>>> a = [1,2,3]
>>> [x if x & 1 else 'even' for x in a]
[1, 'even', 3]
You're mixing the if clause of the list comprehension up with a
ternary expresssion. There's no "else" in the list comprehension if
clause.
Paul
On 5 October 2017 at 16:40, Jason H wrote:
a = [1,2,3]
[ x for x in
[x if x & 1 else 'even' for x in a]
An `if` at the end of the comprehension means a condition on whether to
include the value.
Also, this question would have been better asked on python-list.
2017-10-05 8:40 GMT-07:00 Jason H :
> >>> a = [1,2,3]
> >>> [ x for x in a if x & 1]
> [1, 3]
> >>> [
>>> a = [1,2,3]
>>> [ x for x in a if x & 1]
[1, 3]
>>> [ x for x in a if x & 1 else 'even']
File "", line 1
[ x for x in a if x & 1 else 'even']
^
SyntaxError: invalid syntax
I expected [1, 'even', 3]
I would expect that the if expression would be able to