How to Break out of multiple loops in Python ?
Last Updated :
24 Feb, 2023
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
Similar Reads
How to Check End of For Loop in Python In Python, we often use loops to iterate over a collection like list or string. But sometimes, we may want to know when the loop has reached its end. There are different ways to check for the end of a for loop. Let's go through some simple methods to do this.Using else with For Loop (Most Efficient)
2 min read
How to Parallelize a While loop in Python? Parallelizing a while loop in Python involves distributing the iterations of a loop across multiple processing units such as the CPU cores or computing nodes to execute them concurrently. This can significantly reduce the overall execution time of the loop, especially for tasks that are CPU-bound or
2 min read
How to skip Iterations in For Loop - Python Loops are generally used to repeat the tasks. Sometimes, we may want to skip certain steps in the loop. We can do this easily with the continue statement. This article explains how to skip iterations in a for loop.In a for loop, you can use continue to skip a specific iteration when a condition is t
2 min read
How to Emulate a Do-while loop in Python? We have given a list of strings and we need to emulate the list of strings using the Do-while loop and print the result. In this article, we will take a list of strings and then emulate it using a Do-while loop. Do while loop is a type of control looping statement that can run any statement until th
3 min read
Provide Multiple Statements on a Single Line in Python Python is known for its readability and simplicity, allowing developers to express concepts concisely. While it generally encourages clear and straightforward code, there are scenarios where you might want to execute multiple statements on a single line. In this article, we'll explore the logic, and
3 min read
How To Catch A Keyboardinterrupt in Python In Python, KeyboardInterrupt is a built-in exception that occurs when the user interrupts the execution of a program using a keyboard action, typically by pressing Ctrl+C. Handling KeyboardInterrupt is crucial, especially in scenarios where a program involves time-consuming operations or user intera
2 min read
How to Keep a Python Script Output Window Open? We have the task of how to keep a Python script output window open in Python. This article will show some generally used methods of how to keep a Python script output window open in Python. Keeping a Python script output window open after execution is a common challenge, especially when running scri
2 min read
Two For Loops in List Comprehension - Python List comprehension is a concise and readable way to create lists in Python. Using two for loops in list comprehension is a great way to handle nested iterations and generate complex lists. Using two for-loopsThis is the simplest and most efficient way to write two for loops in a list comprehension.
2 min read
How to Kill a While Loop with a Keystroke in Python? While loops are used to repeatedly execute a block of code until a condition is met. But what if you want the user to stop the loop manually, say by pressing a key? Then you can do so by pressing a key. This article covers three simple ways to break a while loop using a keystroke:Using KeyboardInter
2 min read