Ideas about optional filter on for loop statements

Larry Bates lbates at swamisoft.com
Tue May 11 14:41:52 EDT 2004


Brian,

How about writing:

for x in [i for i in range(10) if i%2 is 0]:
    print x

or in your other examples:

for x in [i for i in l if i]:
...

for x in [i for i in l if not i]:
...

All seem exteremely close to your proposal but
don't require any changes to current language
implementation (e.g. just use list comprehensions).

Regards,
Larry Bates
Syscon, Inc.

"Brian L." <bluczkie at andrew.cmu.edu> wrote in message
news:c186c44d.0405110926.5eead044 at posting.google.com...
> After following the discussion on Generator expressions on python-dev
> for the last few weeks, and finally getting used to list
> comprehensions as opposed to map/filter, it occurred to me that the
> for loop statement lacks the filtering feature when compared to the
> listcomp/genexp. For instance,
>
> (real code)
> for x in range(10):
>     if x%2 is 0:
>         print x
>
> Could be reduced to: (fake code)
>
> for x in range(10) if x%2 is 0:
>     print x
>
> Which is comparable to iterating and printing the elements of the
> listcomp:
> [x for x in range(10) if x%2 is 0]
>
> or the genexp: (this syntax isn't real yet, but I'd imagine this to be
> fairly accurate based on python-dev)
>
> (x for x in range(10) if x%2 is 0)
>
> Note the perfect consistency between all three iterator usages.
>
> This change would not break any compatibility that I can think of, but
> would improve self-consistency within python. Furthermore, if
> listcomps and genexps are a direction that python is moving in, then
> it would probably make sense that the for loop statement has an
> optional filtering clause as  well.
>
> The strongest argument I can think of against it is that for loop
> statements should be reserved for iteration only, and that they
> shouldn't have functional features (for instance, the for loop can not
> and will not ever have 'map' like semantics, so why should it have
> filter?). I don't think, however that this is a problem, and
> considering the number of times that I've written loops in the
> following patterns:
>
> for x in l:
>     if x is None: continue
>     ...
>
> or
>
> for x in l:
>     if x is not None:
>         ...
>
> I think that a more pythonic syntax may be in order.
>
> for x in l if x is not None:
>     ...
>
> is certainly cleaner and easier to read. This clause should of course
> be optional
>
> Thoughts?
>
> If this receives enough positive attention on comp.lang.python, then
> I'll write it up and submit a PEP.
>
> Brian





More information about the Python-list mailing list