[Python-ideas] Is this PEP-able? for X in ListY while conditionZ:

Stephen J. Turnbull stephen at xemacs.org
Thu Jun 27 07:55:49 CEST 2013


Andrew Barnert writes:
 > Compare:
 > 
 > >     [x for x in range(n) if n<10 else range(10)]
 > 
 > I don't think that's valid (although I'm not sure without testing).

It's not.  Just add parentheses to get a ternary expression:

>>> n = 11
>>> [x for x in range(n) if n<10 else range(10)] 
  File "<stdin>", line 1
    [x for x in range(n) if n<10 else range(10)] 
                                    ^
SyntaxError: invalid syntax
>>> [x for x in (range(n) if n<10 else range(10))]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> 

Python 3.2.5 on Mac OS X


More information about the Python-ideas mailing list