On Fri, Aug 30, 2013 at 8:17 AM, Ben Finney <ben+pyt...@benfinney.id.au> wrote: > Fábio Santos <fabiosantos...@gmail.com> writes: > >> It is a shame that this is not possible in python. for..if exists in >> comprehensions and not in regular loops but that would be nice >> sometimes. > > So you use it in a generator expression, and iterate over the generator: > > for foo in (spam for spam in sequence if predicate(spam)): > process(spam) > > That way, there's no need for new syntax.
That works for the specific example of a for loop (and proves that it's logical and sensible to iterate over part of a loop). But how many times has something similar come up - like the while-loop-that-retains-its-value suggestion a while ago? Sometimes, the only "new syntax" required is a weakening of the rule that one thing goes on one line, and then the syntax is simply two block constructs forming a single loop header. Also, the genexp version you have above seems to repeat itself a lot. I'd write that as simply: for spam in sequence: if predicate(spam): process(spam) though of course, if the processing is a single function call, there are other ways to lay it out. But assume that the processing is a full suite. ChrisA -- http://mail.python.org/mailman/listinfo/python-list