strange syntax rules on list comprehension conditions

Nicholas nicholasinparis at gmail.com
Fri Jan 18 13:53:22 EST 2008


I was quite delighted today, after extensive searches yielded nothing, to
discover how to place an else condition in a list comprehension.
Trivial mask example:
>>> [True if i <5 else False for i in range(10)]       # A
[True, True, True, True, True, False, False, False, False, False]

I then experimented to drop the else statement which yields an error
>>> [i if i>3 for i in range(10)]
Traceback (  File "<interactive input>", line 1
this syntax works of course
>>> [i if i>3 else i for i in range(10)]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Does anybody else find this lack of symmetry odd?

Nicholas
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080118/0a06c04a/attachment.html>


More information about the Python-list mailing list