for: else: - any practical uses for the else clause?

Ben Sizer kylotan at
Wed Sep 27 16:15:08 CEST 2006

skip at wrote:
> metaperl> I'm wondering if anyone has ever found a practical use for the
>     metaperl> else branch?
> Yeah, I use it from time to time:
>     for foo in bar:
>         if foo matches some condition:
>             print "sail to tahiti!"
>             break
>     else:
>         print "abandon ship!"

As a C++ programmer (which I'm sure undermines my argument before
you've even read it...), this feels 'backwards' to me. Although I am no
purist, the 'else' typically implies failure of a previous explicit
condition, yet in this case, it's executed by default, when the
previous clause was successfully executed. It would seem more natural
if the else clause was triggered by 'bar' being empty, or even if the
loop was explicitly broken out of, though I'm sure that would make the
construct much less useful.

Ben Sizer

More information about the Python-list mailing list