[Python-ideas] A conditional "for" statement

Chris Rebert pyideas at rebertia.com
Fri Apr 24 00:34:58 CEST 2009


On Thu, Apr 23, 2009 at 3:29 PM, Michael S. Gilbert
<michael.s.gilbert at gmail.com> wrote:
> Hello,
>
> I've recently been working on some code where i am processing a
> list, but excluding certain items.  The solution is to use a list
> comprehension in the "for" statement.  An example is:
>
>  for m in [n for n in range( 0 , 5 ) if n != 2]
>
> Determining what's going on here isn't immediately obvious (i.e.
> what's this new variable n doing?).  It would be nice to have a more
> streamlined syntax such as:
>
>  for m in range( 0 , 5 ) with m != 2

I don't see how this is clearer than either of the obvious alternatives:

for m in range(0 , 5):
    if m == 2:
        continue
    #loop body

for m in range(0 , 5):
    if m != 2:
        #loop body

It's certainly /slightly/ shorter, but the problem is not severe
enough to warrant new syntax, imho.
Also, this uses the `with` keyword in a completely different way from
its existing use, which could be confusing.

Cheers,
Chris
-- 
I have a blog:
http://blog.rebertia.com



More information about the Python-ideas mailing list