For Else in Python

I have the unfortunate brain wiring where once I understand something complete, or do some task such that it works, that thing suddenly seems trivial to me. I think this is generally true for most individuals who have spent even as little as a year in a narrow field of study, like programmers with a particular programming language. If you're a half-decent programmer, did you know you could make some money by writing a beginner's book? All that stuff that seems trivial to you now, you could monetize! Or be like me and point to other references that are free...

Anyway, the subject of this post. Python has a construct where the for loop or the while loop have an optional else block you can attach to them. The rule that determines whether the block gets executed or not is at first unintuitive, but it becomes immediately clear with an example.

You probably think the else block should execute only if the loop never ran once? If you think that, you are wrong. The rule is: execute the else block if the loop completed normally; that is, without a break statement. (Or raised exception.)

Before you spend too much time letting that sink in, look at this example:

found = False
for sprite in spritelist:
if is_fommilo(sprite):
found = True
masthe(sprite)
break

print 'No sprite is fommilo'


I tend to write this sort of code more often in languages like Java than Python for some reason... Anyway, the magic of for..else lets us get rid of that outer if check and the found variable:

for sprite in spritelist:
if is_fommilo(sprite):
masthe(sprite)
break
else:
print 'No sprite is fommilo'


The code is more compact and readable. At least if you know what for..else does. It's kind of a stupid name, though I'm not sure what would be better.

In the Lisp world we could just macro up the more intuitive version... I'm starting to regret my "Python doesn't have macros, but it's okay" post. It's not okay.

Posted on 2012-03-21 by Jach

Tags: programming, python, tip

LaTeX allowed in comments, use $\\...\\$\$ to wrap inline and $$...$$ to wrap blocks.