Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Breaking out of nested loops [duplicate]

Is there an easier way to break out of nested loops than throwing an exception? (In Perl, you can give labels to each loop and at least continue an outer loop.)

for x in range(10):     for y in range(10):         print x*y         if x*y > 50:             "break both loops" 

I.e., is there a nicer way than:

class BreakIt(Exception): pass  try:     for x in range(10):         for y in range(10):             print x*y             if x*y > 50:                 raise BreakIt except BreakIt:     pass 
like image 954
Michael Kuhn Avatar asked Mar 17 '09 09:03

Michael Kuhn


People also ask

Does Break break out of nested loops?

Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.

How do I stop too many nested loops?

Originally Answered: How can I avoid nested "for loop" for optimize my code? Sort the array first. Then run once over it and count consecutive elements. For each count larger than 1, compute count-choose-2 and sum them up.


1 Answers

for x in xrange(10):     for y in xrange(10):         print x*y         if x*y > 50:             break     else:         continue  # only executed if the inner loop did NOT break     break  # only executed if the inner loop DID break 

The same works for deeper loops:

for x in xrange(10):     for y in xrange(10):         for z in xrange(10):             print x,y,z             if x*y*z == 30:                 break         else:             continue         break     else:         continue     break 
like image 111
Markus Jarderot Avatar answered Oct 19 '22 22:10

Markus Jarderot