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 "<stdin>", line 1
>     [ x for x  in a if x & 1 else 'even']
>                                 ^
> SyntaxError: invalid syntax

[(x if x & 1 else 'even') for x in a]


The if clause in the list comprehension determines which items are 
included, and there is no "else" allowed. You don't want to skip any 
values: the list comp should have the same number of items as "a" 
(namely, 3) the comprehension if clause is inappropriate.

Instead, you want the value in the comprehension to conditionally depend 
on x.

By the way, this list is for suggesting improvements and new 
functionality to the language, not for asking for help. You should 
consider asking your questions on python-list or tutor mailing lists 
instead.


-- 
Steve
_______________________________________________
Python-ideas mailing list
Python-ideas@python.org
https://mail.python.org/mailman/listinfo/python-ideas
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to