[Python-ideas] if-statement in for-loop

Nick Coghlan ncoghlan at gmail.com
Tue Oct 4 07:37:04 EDT 2016


On 4 October 2016 at 14:32, Ken Kundert <admin at shalmirane.com> wrote:
> For example, it was suggested that one could simplify a multi-level loop by
> moving the multiple levels of for loop into a separate function that acts as
> generator. And that is a nice idea, but when writing it, the writing of the
> generator function represents a speed bump. Whereas writing something like the
> following is simple, compact, quick, and obvious. There is no reason why it
> should not be allowed even though it might not always be the best approach to
> use:
>
>     for i in range(5) for j in range(5) for k in range(5):
>         ...
>
> And I would really like to be able to write loops of the form:
>
>     for item in items if item is not None:
>        ...
>
> It is something I do all the time, and it would be nice if it did not consume
> two levels on indentation.

And when you add the "else" clause that's supported by both "for" and
"if", what does that mean in the abbreviated form?

    for item in items if item is not None:
        ...
    else:
        # ???

Or is the implicit proposal that this form be special cased to
disallow the "else" clause?

Comprehensions don't have that concern, as they don't support "else"
clauses at all.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list