Python snippet: for…else

Python has a clever for...else (albeit ancient by now) construct allowing the use of an else suite. Consider the following example, written without the for…else construct:

contains_even = False
for element in [1, 2, 3, 4, 5]:
    if element % 2 == 0:
        contains_even = True
        break
if contains_even:
    print "List contains an even element."
else:
    print "List does not contain an even element."

Compare that to the for…else equivalent code, allowing us to remove an additional flag variable:

for element in [1, 2, 3, 4, 5]:
    if element % 2 == 0:
        print "List contains an even element."
        break
else:
    print "List does not contain an even element."

The else suite will be executed unless the preceding loop has been terminated by a break statement. A continue statement will skip the rest of the suite and proceed with the next item, or with the else clause if there was no items remaining.

This entry was posted in Development, Python. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.
  • Emilio Cuberos

    :-O good to know!

  • Anonymous

    Useful, thanks. :) According to my limited Google skills ruby lacks this loop feature. Quite interesting since many other handy features from Python are implemented in Ruby as well.

    Python <3