Start New Discussion within our Software Development Community

Some computer languages have a goto statement to break out of deeply nested loops. Python has chosen not to implement the much abused goto. There are other, really more elegant, ways to accomplish the same outcome. Here are three examples.

# Break out of a nested for loop when 'emma' is reached
# Python does not have a goto statement to do this!
# Tested with Python24     vegaseat     12sep2006

# create a list of lists ...
list1 = [['frank', 'joe', 'mary'], ['carl', 'emma', 'jerry'], ['harry', 'matt', 'sue']]

# you can set a flag ...
done = False
for list2 in list1:
    if done:
        break
    for item in list2:
        print item
        if item == 'emma':
            done = True
            # this break only breaks out of this inner loop
            # needs the 'if done' to carry it out of all loops
            break

print

# or raise an exception ...
try:
    for list2 in list1:
        for item in list2:
            print item
            if item == 'emma':
                # raise an exception
                raise StopIteration()
except StopIteration:
    pass

print

# or use a function and force a return ...
def break_nestedloop(list1):
    for list2 in list1:
        for item in list2:
            print item
            if item == 'emma':
                # force a return
                return

dummy = break_nestedloop(list1)  # returns None

I like the middle one the best, in terms of flexibility and conceptual cleanness. The function version is nice, except that it would require a different function for each nested loop (unless your loops were similar enough that you could polymorph them...). The flag version is fastest, I would guess, but it's less human-readable. It also requires a check at each level, which would be ugly at 5+ levels of nesting.

OH ... and the middle version works more efficiently with recursion, also.

All opinions expressed here are highly subjective...

BTW, are there any other legitmate uses of 'goto'? I've only ever heard the "break out of nested loops" and "recover from errors in nested functions" cited.

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.