[Python-ideas] filter-only list comps

Nick Coghlan ncoghlan at gmail.com
Thu Feb 25 14:43:25 CET 2010

spir wrote:
> numbers if x%2==1] that confusingly repeats the item. Would there be
> any parsing issue if we let down "<expression> for" when it does
> nothing?

Yes, there's a parsing problem:

"x in numbers" is a containment test

"x in numbers if cond else whatever" is a containment test combined with
a conditional expression

"x for x in numbers" and "x for x in numbers if cond" are
genexps/comprehensions (depending on the kind of brackets you put around
them, if any)

"x in number if cond" is none of the above, but the parser can't tell it
isn't meant to be the second one and hence will choke on the missing "else":

>>> 1 in [] if True
  File "<stdin>", line 1
    1 in [] if True
SyntaxError: invalid syntax
>>> 1 in [] if True else None

Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list