Friday, December 27, 2024
Google search engine
HomeLanguagesHow to Break out of multiple loops in Python ?

How to Break out of multiple loops in Python ?

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):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x:
            if j == x:
                print('Element found')
                break
            else:
                print(j)
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


Output:

1
2
3
Element found
7
8
9

Time complexity: O(n^2) where n is the number of elements in the input list of lists. 

Auxiliary space: O(1) as we are not using any additional data structures to store information.

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




# Python code to break out of
# multiple loops by defining a
# function and using return statement
 
 
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x and returning
            # the function if such element is found
            # else printing the element:
            if j == x:
                print('Element found')
                return
            else:
                print(j)
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


Output:

1
2
3
Element found

Time complexity: O(n^2), where n is the total number of elements in all the nested lists in the arr.
Auxiliary space: O(1), as we are not using any additional data structure to store the elements or intermediate results.

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




# Python code to break out of multiple
# loops by using an else block
 
 
def elementInArray(arr, x):
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x:
            if j == x:
                print('Element found')
                break
            else:
                print(j)
                 
        # If the inner loop completes without encountering
        # the break statement then the following else
        # block will be executed and outer loop will
        # continue to the next value of i:
        else:
            continue
             
        # If the inner loop terminates due to the
        # break statement, the else block will not
        # be executed and the following break
        # statement will terminate the outer loop also:
        break
 
 
# Driver Code:
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




# Python code to break out of multiple
# loops by using a flag variable
 
 
def elementInArray(arr, x):
    flag = False  # Defining the flag variable
 
    # Iterating through all
    # lists present in arr:
    for i in arr:
       
        # Iterating through all the elements
        # of each of the nested lists in arr:
        for j in i:
 
            # Checking if any element in the
            # nested list is equal to x
            # and assigning True value to
            # flag if the condition is met
            # else printing the element j:
            if j == x:
                flag = True
                print('Element found')
                break
            else:
                print(j)
                 
        # If the inner loop terminates due to
        # the break statement and flag is True
        # then the following if block will
        # be executed and the break statement in it
        # will also terminate the outer loop. Else,
        # the outer loop will continue:
        if flag == True:
            break
 
 
# Driver Code:
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
x = 4
elementInArray(arr, x)


Output:

1
2
3
Element found

RELATED ARTICLES

Most Popular

Recent Comments