0

After finding the first list1[k] > list2[m,0] I want to increase the the value of list2[m,1]. The main thing is that after the first found value and increase of list2[m,1] I dont want to continue the inner for loop. I tried to use break at the end but it didnt work.Any suggestions?

 for k in range(0, rang+1):
    for m in range(0, len(dir)): # len(dir) is the row number of list2 
      if list1[k] > list2[m,0]:
        list2[m,1] += 1  
s900n
  • 3,115
  • 5
  • 27
  • 35

1 Answers1

2

It sounds like you want a "multi-level break", a statement that can break out of two or more loops at once.

Some languages have such a thing, but Python doesn't.

But there are a few things you can do instead, in order from the usually-best solution down to don't-ever-do-this.


Refactor this into a function. When you return from a function, it breaks out of any loops you're in, all the way to the edge of the function.


Use a custom exception. For example, class BreakException(Exception): pass. Then wrap a try: / except BreakException: pass around the outer loop. Then just raise BreakException() to break. When you raise an exception, it breaks out of any loops you're in, all the way to the except statement.


Use explicit flags to keep track of what you're doing. Put doublebreak = False before the inner loop, and if doublebreak: break after the inner loop, then do doublebreak = True; break inside the inner loop.


Google for some bytecode hacks that add a way to do multi-level breaks (with some slightly ugly syntax) to the language, and build an import hook around them. (Or maybe use MacroPy instead.)


Google for the even uglier hacks that add goto support to Python; you can easily simulate labeled breaks with goto, and labeled breaks are usually a good substitute for multi-level breaks.

abarnert
  • 354,177
  • 51
  • 601
  • 671
  • 1
    Why `class BreakException(RuntimeError)` and not simply `class BreakException(Exception)` as this is clearly not an error but a desired behaviour ? – Ara Oct 21 '14 at 22:25
  • @Ara: Good point; fixed. I originally had a long spiel about pre-2.5 exceptions, which I stripped out, but left behind the ugly workaround for no good reason… Thanks for catching it. – abarnert Oct 21 '14 at 22:41