Ideas about optional filter on for loop statements

Brian L. bluczkie at andrew.cmu.edu
Tue May 11 13:26:48 EDT 2004


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