[Python-Dev] for...else

Alexander Belopolsky alexander.belopolsky at gmail.com
Mon Jul 24 12:36:44 EDT 2017


On Mon, Jul 24, 2017 at 12:23 PM, Ben Hoyt <benhoyt at gmail.com> wrote:
> .. I found a kind of mnemonic to help me remember when the
> "else" part happens: I think of it not as "for ... else" but as "break ...
> else" -- saying it this way makes it clear to me that the break goes with
> the else. "If this condition inside the loop is true, break. ... *else* if
> we didn't break, do this other thing after the loop."

Note that since break itself is typically guarded by an "if" as in

for i in x:
    ...
    if cond(i):
        break
    ...
else:
    ...

you can match the "else" above to the "if" inside the loop.


More information about the Python-Dev mailing list