[Python-ideas] for-loop-if like list comps have?

Steven D'Aprano steve at pearwood.info
Sat Mar 15 03:37:48 CET 2014


On Fri, Mar 14, 2014 at 09:07:18PM -0500, Christopher Welborn wrote:
> mylist = ['apple', 'banana', 'orange', 'grapefruit']
> 
> # Why is this okay...
>     for item in [x for x in mylist if 'p' in x]:
>         print(item)
> 
> # But this isn't?
>     for item in mylist if 'p' in item:
>     SyntaxError: invalid syntax


This suggestion has been made, oh, a million times -- not that I would 
ever exaggerate... *wink* -- and has been rejected each time.

Personally, I don't think it gains you too much, all you save is one 
line and one nesting level, and if you're nested so deeply that this 
becomes important, your code is probably in desperate need of 
refactoring.

The downside includes additional complication. It's one more thing for 
people to learn. Not only do you have to learn that there are two 
independent features, the for-statement and the if-statement, which 
being independent can be combined however you like:

    # 1
    for x in seq:
        if cond: 
            ...

    #2
    if cond:
        for x in seq:
            ...

but now you also have to learn a *third* form:

    for x in seq if cond:
        ...

and learn that it is the same as #1 above rather than #2 above. And that 
there *isn't* a fourth form:

    if cond for x in seq: 
        ...

or other combinations like:

    while x if cond:
    if cond while x:
    if cond try:
    for x try: 
    for x if y try:


etc. The way statements work in Python is that you combine them by using 
a new line and starting a new block, not by having special syntactic 
forms for each combination.

List comprehensions are different, because they don't create a new 
block, and they are an expression not a statement.


-- 
Steven


More information about the Python-ideas mailing list