How do you use continue in nested for loops in python?

Not as elegant as it should be

Photo by Johannes Plenio on Unsplash

We all know that Python is an elegant programming language. But everything has weaknesses. Sometimes Python is not as elegant as it should be.

For example, when we need to break out of nested loops as follows:

for a in list_a:
for b in list_b:
if condition(a,b)…

break and continue allow you to control the flow of your loops. They’re a concept that beginners to Python tend to misunderstand, so pay careful attention.

Using break

The break statement will completely break out of the current loop, meaning it won’t run any more of the statements contained inside of it.

>>> names = ["Rose", "Max", "Nina", "Phillip"]
>>> for name in names:
...     print(f"Hello, {name}")
...     if name == "Nina":
...         break
...
Hello, Rose
Hello, Max
Hello, Nina

break completely breaks out of the loop.

Using continue

continue works a little differently. Instead, it goes back to the start of the loop, skipping over any other statements contained within the loop.

>>> for name in names:
...     if name != "Nina":
...         continue
...     print(f"Hello, {name}")
...
Hello, Nina

continue continues to the start of the loop

break and continue visualized

What happens when we run the code from this Python file?

# Python file names.py
names = ["Jimmy", "Rose", "Max", "Nina", "Phillip"]

for name in names:
    if len(name) != 4:
        continue

    print(f"Hello, {name}")

    if name == "Nina":
        break

print("Done!")

How do you use continue in nested for loops in python?

Results

See if you can guess the results before expanding this section.

Using break and continue in nested loops.

Remember, break and continue only work for the current loop. Even though I’ve been programming Python for years, this is something that still trips me up!

>>> names = ["Rose", "Max", "Nina"]
>>> target_letter = 'x'
>>> for name in names:
...     print(f"{name} in outer loop")
...     for char in name:
...             if char == target_letter:
...                 print(f"Found {name} with letter: {target_letter}")
...                 print("breaking out of inner loop")
...                 break
...
Rose in outer loop
Max in outer loop
Found Max with letter: x
breaking out of inner loop
Nina in outer loop
>>>

break in the inner loop only breaks out of the inner loop! The outer loop continues to run.

Loop Control in while loops

You can also use break and continue in while loops. One common scenario is running a loop forever, until a certain condition is met.

>>> count = 0 
>>> while True:
...     count += 1
...     if count == 5:
...             print("Count reached")
...             break
...
Count reached

Be careful that your condition will eventually be met, or else your program will get stuck in an infinite loop. For production use, it’s better to use asynchronous programming.

Loops and the return statement

Just like in functions, consider the return statement the hard kill-switch of the loop.

>>> def name_length(names):
...     for name in names:
...             print(name)
...             if name == "Nina":
...                     return "Found the special name"
...
>>> names = ["Max", "Nina", "Rose"]
>>> name_length(names)
Max
Nina
'Found the special name'

In this article, we will see how to break out of multiple loops in Python. For example, we are given a list of lists arr and an integer x. The task is to iterate through each nested list in order and keep displaying the elements until an element equal to x is found. If such an element is found, an appropriate message is displayed and the code must stop displaying any more elements.

Example:

Input: arr = [[10, 20, 30], [40, 50, 60, 70]], x = 50
Output:
10
20
30
40
Element found

A direct approach to this problem is to iterate through all the elements of arr using a for loop and to use a nested for loop to iterate through all the elements of each of the nested lists in arr and keep printing them. If an element equal to x is encountered, the appropriate message is displayed and the code must break out of both the loops.

However, if we simply use a single break statement, the code will only terminate the inner loop and the outer loop will continue to run, which we do not want to happen. 

Python3

def elementInArray(arr, x):

    for i in arr:

        for j in i:

            if j == x:

                print('Element found')

                break

            else:

                print(j)

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

x = 4

elementInArray(arr, x)

Output:

1
2
3
Element found
7
8
9

In the above case, as soon as 4 has been found, the break statement terminated the inner loop and all the other elements of the same nested list (5, 6) have been skipped, but the code didn’t terminate the outer loop which then proceeded to the next nested list and also printed all of its elements.

Method 1: Using the return statement

Define a function and place the loops within that function. Using a return statement can directly end the function, thus breaking out of all the loops.

Python3

def elementInArray(arr, x):

    for i in arr:

        for j in i:

            if j == x:

                print('Element found')

                return

            else:

                print(j)

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

x = 4

elementInArray(arr, x)

Output:

1
2
3
Element found

Method 2: Using else: continue

An easier way to do the same is to use an else block containing a continue statement after the inner loop and then adding a break statement after the else block inside the outer loop. If the inner loop terminates due to a break statement given inside the inner loop, then the else block after the inner loop will not be executed and the break statement after the else block will terminate the outer loop also. On the other hand, if the inner loop completes without encountering any break statement then the else block containing the continue statement will be executed and the outer loop will continue to run. The idea is the same even if the number of loops increases.

Python3

def elementInArray(arr, x):

    for i in arr:

        for j in i:

            if j == x:

                print('Element found')

                break

            else:

                print(j)

        else:

            continue

        break

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

x = 4

elementInArray(arr, x)

Output:

1
2
3
Element found

Method 3: Using a flag variable

Another way of breaking out multiple loops is to initialize a flag variable with a False value. The variable can be assigned a True value just before breaking out of the inner loop. The outer loop must contain an if block after the inner loop. The if block must check the value of the flag variable and contain a break statement. If the flag variable is True, then the if block will be executed and will break out of the inner loop also. Else, the outer loop will continue.

Python3

def elementInArray(arr, x):

    flag = False 

    for i in arr:

        for j in i:

            if j == x:

                flag = True

                print('Element found')

                break

            else:

                print(j)

        if flag == True:

            break

arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

x = 4

elementInArray(arr, x)

Output:

1
2
3
Element found

How do you continue in a nested while loop in Python?

8 Answers.
Break from the inner loop (if there's nothing else after it).
Put the outer loop's body in a function and return from the function..
Raise an exception and catch it at the outer level..
Set a flag, break from the inner loop and test it at an outer level..
Refactor the code so you no longer have to do this..

How do I use continue in nested loops?

When continue statement is used in a nested loop, it only skips the current execution of the inner loop. Java continue statement can be used with label to skip the current iteration of the outer loop too.

Can you use continue in a for loop Python?

The continue statement can be used in both while and for loops.

How do you break and continue in nested for loop?

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.