continue and break frustration

Carl Banks imbosol at aerojockey.invalid
Mon Dec 15 04:03:52 CET 2003

Glen Wheeler wrote:
>  Hello All.
>  I've been coding in python for a reasonable amount of time now
> (coding in total for approx. 20 years) and am writing a performance
> intensive program in python.
>  The problem I'm having is I want to use break and continue to get
> out from more than one level of loop.  If I set a variable and then
> check it my program will take too much of a performance hit.
>  Are there any alternatives people can think of?

One thing you can do is use an else clause on your inner loop(s) to
continue the surrounding loop.  Then, following the else statement,
put in a break.  Then, a break in the innermost loop will cascade back
to the top level.

To illustrate:

    for i in xrange(100):
        for j in xrange(100):
            if (i,j) == (45,55):
                # Found a match.
                # Break out of the inner loop.
            # No match was encountered in the inner loop.
            # Continue the outer loop.
        # The inner loop must have found a match.
        # So, break out of the outer loop, too.

For the above example, this gave me a not-quite-one-percent speed
increase over the version using a variable.  YMMV.

CARL BANKS         
"If you believe in yourself, drink your school, stay on drugs, and
don't do milk, you can get work."
          -- Parody of Mr. T from a Robert Smigel Cartoon

More information about the Python-list mailing list