<div dir="ltr">[x if x & 1 else 'even' for x in a]<div><br></div><div>An `if` at the end of the comprehension means a condition on whether to include the value.</div><div><br></div><div>Also, this question would have been better asked on python-list.</div></div><div class="gmail_extra"><br><div class="gmail_quote">2017-10-05 8:40 GMT-07:00 Jason H <span dir="ltr"><<a href="mailto:jhihn@gmx.com" target="_blank">jhihn@gmx.com</a>></span>:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">>>> a = [1,2,3]<br>
>>> [ x for x in a if x & 1]<br>
[1, 3]<br>
>>> [ x for x in a if x & 1 else 'even']<br>
File "<stdin>", line 1<br>
[ x for x in a if x & 1 else 'even']<br>
^<br>
SyntaxError: invalid syntax<br>
<br>
I expected [1, 'even', 3]<br>
<br>
I would expect that the if expression would be able to provide alternative values through else.<br>
<br>
The work around blows it out to:<br>
l = []<br>
for x in a:<br>
if x&1:<br>
l.append(x)<br>
else:<br>
l.append('even')<br>
<br>
<br>
Unless there is a better way?<br>
______________________________<wbr>_________________<br>
Python-ideas mailing list<br>
<a href="mailto:Python-ideas@python.org">Python-ideas@python.org</a><br>
<a href="https://mail.python.org/mailman/listinfo/python-ideas" rel="noreferrer" target="_blank">https://mail.python.org/<wbr>mailman/listinfo/python-ideas</a><br>
Code of Conduct: <a href="http://python.org/psf/codeofconduct/" rel="noreferrer" target="_blank">http://python.org/psf/<wbr>codeofconduct/</a><br>
</blockquote></div><br></div>