for-else loops

| categories: programming | tags: | View Comments

I just learned of for/else loops (http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho). They are interesting enough to write about. The idea is that there is an "else" clause of a for loop that is only executed if the loop completes without a break statement. The use case is to avoid using a flag. For example, let us say we want to loop through a list and determine if a number exists. Here is a typical way you might think to do it:

def f():
    flag = False
    for i in range(10):
        if i == 5:
            flag = True
            break

    return flag

print f()
True

A for/else loop does this in a different way. Essentially, the else clause runs if the loop completes, otherwise if the break occurs it is skipped. In this example the break statement occurs, so the else statement is skipped.

def f():
    for i in range(10):
        if i == 5:
            break
    else:
        return False

    return True

print f()
True

In this example no break statement occurs, so the else clause is executed.

def f():
    for i in range(10):
        if i == 15:
            break
    else:
        return False

    return True

print f()
False

It is hard to say if this is an improvement over the flag. They both use the same number of lines of code, and I find it debatable if the else statement is intuitive in its meaning. Maybe if there were multiple potential breaks this would be better.

Needless to say, go watch http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho. You will learn a lot of interesting things!

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

blog comments powered by Disqus