What is `suite` and `else` in Python's for grammar rule?

Viewed 1915

Python3 defines for loop as for_stmt: 'for' exprlist 'in' testlist ':' suite ['else' ':' suite] in the grammar book. suite is defined as suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT.

For me, it's hard to understand how double for loop fits in the grammar description for list comprehension.

There are several smaller questions:

  • And what about else? I assume it's used for list comprehension.
  • Then does a normal for loop can use else block?

I'd appreciate if you can come with examples.

3 Answers

As you can see from the other rules of the grammar:

suite: simple_stmt | NEWLINE INDENT stmt+ DEDENT

suite is either a simple statement (in one line), e.g.:

for foo in bar: some_statement()

or it is a newline, followed by an indented block (which consists of statements).


'else' is simply the string "else".

I usually read the else of a for-loop as "no-break": It is executed after the for-loop is finished, but only if it wasn't exited by break. The reason it exists is consistency with while, which has an else statement, as it's basically just a repeated if.

According to the documentation, the else clause of a for loop is executed if the loop ended without having been broken.

See these two examples:

for elem in range(5):
    print(elem)
else:
    print('ended')

Here, the suite part correspond to print(elem), and the output will be:

0
1
2
3
4
ended

And second:

for elem in range(5):
    if elem < 3:
        print(elem)
    else:
        break
else:
    print('ended')

Here, the suite part correspond to if elem < 3: print(elem) else: break, and the output will be:

0
1
2
Related