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

Andrew Barnert abarnert at yahoo.com
Sat Mar 15 03:43:32 CET 2014


On Mar 14, 2014, at 19:07, Christopher Welborn <cjwelborn at live.com> 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
> 
> # Instead you have to do another nesting level..
>    for item in mylist:
>        if 'p' in item:
>            print(item)
> 
> # Or another way.
>    for item in mylist:
>        if 'p' not in item:
>            continue
>        print(item)
> 
> ...And there is 'filter', 'lambdas', and whatever else
> to achieve the same result. But the list comprehension
> is already closely related to a for-loop, and it seems
> natural to go from:
>    [x for x in mylist if x]
> to:
>    for x in mylist if x:
> 
> Just an idea, sorry if it has been mentioned before.

In a listcomp, each for or if is a separate clause, and they can be nested any way you want (except for the restriction that the first clause has to be a for). So, you can do this:

    [x for xs in xss for x in xs]
    [x for x in xs if x if x-1]
    [x for xs in xss if xs for x in xs if x]

Should you be able to write all of those as one-liner statements?

And this isn't just a weird quirk of syntax; each clause is conceptually exactly the same as a nested statement (except for some minor differences with the first one); that's how comprehensions are defined in the language reference.

Not all languages do comprehensions this way; Clojure, Racket, etc. have only for loop clauses in their comprehensions, but every for loop clause has an optional if phrase. Which would make your translation obviously right, instead of wrong for a hard to notice reason. (And it would make comprehensions slightly easier to explain. And it would also make it easier to add things like a while phrase, which people keep asking for.) But that would be a pretty big change for Python at this point.


More information about the Python-ideas mailing list