Speno's Pythonic Avocado 23.12.2003

2003-12-23

Using for loops with else clauses

I went a long time before ever using an else: clause in a python for loop, mainly because I just never needed it. Then one day it hit me that it was perfect for what I needed to do. The idea is that code in the else: clause is only executed if we don't encounter a break statement in the body of the for loop. See The for statement in the Python documentation for details.

Here's an example of how I've recently used the for loop's else: clause.

YUCKY_STUFF = [ 'sugar', 'wheat', 'high fructose corn syrup', 'soybean', 'peanut', ] for food in foods: for ingredient in YUCKY_STUFF: if food.find(ingredient) != -1: break else: consume(food)

The code above shows a way to exclude certain unwanted items from a sequence. In this case we skip a food if it contains any of the things defined in the YUCKY_STUFF list. Those that aren't excluded are consume()'d. This "exclude if any condition is true" pattern seems like a very natural way to use a for loop's else clause.

Take care.

posted at 21:50:40    #    comment []    trackback []
December 2003
MoTuWeThFrSaSu
1 2 3 4 5 6 7
8 91011121314
15161718192021
22232425262728
293031    
Nov
2003
 Jan
2004

One python programmer's search for understanding and avocados. This isn't personal, only pythonic.

XML-Image Letterimage

© 2003-2005, John P. Speno