6

It seems both of the below codes are printing the same, then what is the need of "else" block after "for" loop in python.

Code 1:

for i in range(10):
    print i
else:
    print "after for loop"

Code 2:

for i in range(10):
    print i

print "after for loop"

Thanks in advance.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Rajesh Kumar
  • 1,270
  • 4
  • 15
  • 31

3 Answers3

7

From the documentation:

Loop statements may have an else clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.

Follow the link for an example how this can be used.

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
4

else executes after for providing for wasn't terminated with break:

for i in range(10):
    print i
    if i == 8:
        break # termination, no else    
else:
    print "after for loop"
wjandrea
  • 28,235
  • 9
  • 60
  • 81
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
1

This was originally enacted in order to get rid of all the "GOTO" statements in procedures without using flags: It means "NO BREAK"

for i, value in enumerate(sequence):
    if value == target:
        break
else:           #<-- if we finish the loop and did not encounter break, return -1
    return -1
return 1        #<-- if we did encounter break, return 1

You can watch Raymond Hettinger's Pycon talk that mentions the for/else construct here: Transforming Code into Beautiful, Idiomatic Python

wjandrea
  • 28,235
  • 9
  • 60
  • 81
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80