[Python-ideas] Ternary operators in list comprehensions

Rob Cliffe rob.cliffe at btinternet.com
Thu Oct 5 12:24:42 EDT 2017


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 line of code.

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

Other variants may be possible.  Whereas Jelle's correct version can be 
written as

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

Rob Cliffe


On 05/10/2017 16:44, Jelle Zijlstra wrote:
> [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 <jhihn at gmxcom <mailto:jhihn at gmx.com>>:
>
>     >>> 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
>
>     I expected [1, 'even', 3]
>
>     I would expect that the if expression would be able to provide
>     alternative values through else.
>
>     The work around blows it out to:
>     l = []
>     for x in a:
>       if x&1:
>         l.append(x)
>       else:
>         l.append('even')
>
>
>     Unless there is a better way?
>     _______________________________________________
>     Python-ideas mailing list
>     Python-ideas at python.org <mailto:Python-ideas at python.org>
>     https://mail.python.org/mailman/listinfo/python-ideas
>     <https://mail.python.org/mailman/listinfo/python-ideas>
>     Code of Conduct: http://python.org/psf/codeofconduct/
>     <http://python.org/psf/codeofconduct/>
>
>
>
> <http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient> 
> 	Virus-free. www.avg.com 
> <http://www.avg.com/email-signature?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=emailclient> 
>
>
> <#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171005/45986975/attachment.html>


More information about the Python-ideas mailing list