Breaking out of Nested For Loops (Python)

vegaseat 1 Tallied Votes 3K Views Share

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
jrcagle 77 Practically a Master Poster

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.