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.

2
  • 1
    I think here it is very well explained: psung.blogspot.gr/2007/12/for-else-in-python.html Commented Aug 8, 2014 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). Commented Aug 8, 2014 at 13:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.