1

I came across some code that has the structure:

for val in list:
   do_something(val)
   if val is x:
       break
else:
   do_something_else()

I couldn't find much information about this structure except that the else block won't be executed unless the for loop both executes, and finishes executing without hitting the break.

What would this be used for?

Is there a reason for it not being named something like 'finally', since that would seem to make more logical sense?

Thanks.

flau
  • 1,328
  • 1
  • 20
  • 36
  • 1
    I think here it is very well explained: http://psung.blogspot.gr/2007/12/for-else-in-python.html – billpcs Aug 08 '14 at 13:18
  • `else` might not be the best keyword for this, but `finally` would be plain wrong (if you look what it does in `try-except`). – Matthias Aug 08 '14 at 13:31

1 Answers1

1

Look on this question Else clause on Python while statement In two words this construction can be used for cases, when you need to do something after a loop, but you don't want to it it if loop was broken (by break statement). That's why it is not like 'finally' which are being executed in ANY case.

Community
  • 1
  • 1
The Godfather
  • 4,235
  • 4
  • 39
  • 61