Python What's New

Break Nested Loops in python

break nested loop

Python is very user-friendly programming language and it is most used language now days as it is used in different segments on this IT industry.

Well, Python is sometimes bit tricky, and we spent hours to find the correct solutions of small small problems. I have faced this issue some days ago and spend some hours to find the correct solution. Well, there is no correct solution of any problem,

I have listed 5 solutions to break nested loops, you can choose and use whatever you like and find effective.

Problem: How to break nested loops in python ?

Well the first thing hit our mind when we say break our loop is “Break” statement, but in case of nested loop it only break the 1st level loop where break statement is used. Well, here are the some different methods which you can use to break out of nested loops.

for p in list_p:
    for q in list_q:
        if condition():
            break

In the above case, it will only break from the List_q loop not from the the List P loop.

Well in PHP, Break statement also accept the optional parameter which define the level of loops to break. but in python, there is no such in built

1. Use the condition again

#Using the same condition again
for p in range(6):
    for q in range(7):
        if p==2 and q ==4:
            break
    if p==2 and q ==4:
       break
# and you are out of loop

In this above code, we have used the same conditions and again checking it after exiting out from the first loop and breaking the 2nd required loop.

See also  New version of Google+

2. Use a user-defined flag to break nested loops

# Creating a break flag 
break_now_flag = false
for p in range(6):
    for q in range(7):
        if p==2 and q ==4:
            break_now_flag = true
            break
    if break_now_flag:
        break
# And we will be out from this outer loop

In this above method we set a break flag and make it true when the condition met and check this flag on every iteration of outer loop, if the flag is true, it will break out the outer loop.

3. Use try – catch exception handling mechanism

# Use Try-catch
try:
    for p in range(6):
        for q in range(7):
            if p==2 and q ==4:
                raise StopIteration
except StopIteration:
    print("we are out from the loop")
    pass
# And we will be out from this outer loop

In this above way, we raise an exception when the condition is matched and then catching the exception to break out the loop.

4. Use pythonic for-else

# using for-else loop
for p in range(6):
    for q in range(7):
        if p==2 and q ==4:
            break
    else:
        continue
    break

Well, in the above way, we are using the pythonic approach which is not very well known to users i think. Well In python we have else condition for “For loop” which we are using here.

5. Put this under a function

# define a function for this
def func_check_condition():
    for p in range(6):
        for q in range(7):
            if p==2 and q ==4:
                return

func_check_condition()

Here, we are putting these loops in a function and whenever the condition is met, we are getting out from the loop.

In my opinion the 5th way ( Putting this under a function) is more better to break nested loops than others as in this way, you don’t have to be very much familiar with if-else loop or for-else loops or exception handling.

See also  Get More Insights of your spreadsheet

Also, it is always better to avoid the nested loops as it provide you various complexities and also make the code slower. Well, There are ways which we can use as alternative for nested loops i.e. itertools>product, which gives the Cartesian product of the list, which you can use further for the solution of problem.

About the author

Learning Hub Editorial Team

We are a team of tech enthusiasts who find Google Apps and its features intriguing. Let us know your views if you find us helpful.

Leave a Comment