Wednesday, December 12, 2012

Python: else clause on a for loop

From the "huh, I didn't know you could do that" files:
In [41]: list=[1,2,3]

In [42]: for x in list:
   ....:     print x
   ....: else:
   ....:     print '%s was last' % x
   ....:     
1
2
3
3 was last
It turns out you can have an else clause on loop statements, it will execute as long as the loop exits cleanly (i.e. doesn't break). This includes if 'list' is empty. There's an interesting discussion about its merits here.

No comments: