2

I don't understand why this is allowed in python?

>>> for i in []:
...   print(i)
... else:
...   print('here')
...
here

should this not have else without if syntax error? The else operates every time too (if the for has iterated or not) so its not connected.

>>> for i in 1,2,3:
...   print(i)
... else:
...   print('here')
...
1
2
3
here
Peter Moore
  • 1,632
  • 1
  • 17
  • 31
  • 2
    Your example shows the `else` **not** operating every time. Have you read e.g. https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops? Or e.g. https://stackoverflow.com/q/9979970/3001761? What do you mean *"why"*? – jonrsharpe Feb 15 '19 at 18:18

3 Answers3

6

From the docs

* The else clause executes after the loop completes normally. This means that the loop did not encounter a break statement.*

So this is useful if you are doing a for loop but do not know if the element will be found in the loop/ returned true in the loop. So you can add a break statement to exit the loop if the element is found/true, or execute another command if it is not found/true. For example in your loop:

for i in []:
  print(i)
else:
 print('here')

Output

here

In this case, i was not found in your for loop. However you did not execute a break statement after the for loop. Because of that, the compiler then goes to the else statement to executes the line(s) there since the for loop did not break.

In the second example you have:

for i in 1,2,3:
  print(i)
else:
  print('here')

Output

1
2
3
here

The for loop did not encounter a break statement, so after the for loop is completed it will then execute the else clause. However it you were to use:

for i in 1,2,3:
    print(i)
    break
 else:
    print('here')

Output :

1
Edeki Okoh
  • 1,786
  • 15
  • 27
3

else is executed if we don't break from for.

This can be useful in situation and can help us by saving us from the effort of making flags.

Example:

if we want to execute some code if we don't break from for loop, then normally we would have to do

flag = 0
for i in [1,2,3]:
    if condition:
        flag = 1
        break
if flag == 0:
    do stuff

we can instead do

for i in [1,2,3]:
    if condition:
        break
else:
    do stuff
aj14
  • 63
  • 7
0

You can think about it that: When the break statement is executed in the loop, the code inside the loop following the break statement will be ignored and the loop is finished

if the break statement is not executed, the code following the else statement will be executed after the loop is finished

Mateen Ulhaq and Lance Helsten gave a good example in here Why does python use 'else' after for and while loops?

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")

and

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")

I often use else statement to mark the last turn in for/while loop

lam vu Nguyen
  • 433
  • 4
  • 9
  • I find it logically counter intuitive because in the python if else block use case. Consider if mylist is true as in `if mylist:` the else is never executed. So IMO the reverse case is more in step with the language. `for x in mylist` should only reach the else block `if mylist` is also false to begin with. – Peter Moore Sep 27 '22 at 15:13