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
Append Multiple items to List - Python
Appending items to a list in Python is an essential and common operation when working with different data structures. Sometimes, we need to add more than one item to a list at a time and in this article, we will explore the various ways to append multiple items to a list at the same time.Using exten
2 min read
Remove Multiple Elements from List in Python
In this article, we will explore various methods to remove multiple elements from a list in Python. The simplest way to do this is by using a loop. A simple for loop can also be used to remove multiple elements from a list.Pythona = [10, 20, 30, 40, 50, 60, 70] # Elements to remove remove = [20, 40,
2 min read
How to Comment Out a Block of Code in Python?
In Python, comments allow us to explain code logic, disable code for testing, or make our code more readable to others. While Python does not have a native multiline comment feature like other programming languages, there are multiple ways to comment out a block of code effectively. Let's explore th
2 min read
How to Find Index of Item in Python List
To find the index of given list item in Python, we have multiple methods depending on specific use case. Whether weâre checking for membership, updating an item or extracting information, knowing how to get an index is fundamental. Using index() method is the simplest method to find index of list it
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 Input a List in Python using For Loop
Using a for loop to take list input is a simple and common method. It allows users to enter multiple values one by one, storing them in a list. This approach is flexible and works well when the number of inputs is known in advance.Letâs start with a basic way to input a list using a for loop in Pyth
2 min read
How to Iterate Float List in Python
We are given a list of floats and our task is to iterate the list of floats and print the result. In this article, we will see how to iterate the float list in Python. Example: Input: float_list = [3.14, 2.718, 1.618, 0.707]Output: Using for loop:3.142.7181.6180.707Explanation: Here, we are iteratin
3 min read
How to Take List of Tuples as Input in Python?
Lists of tuples are useful data structures in Python and commonly used when you need to group related elements together while maintaining immutability within each group. We may need to take input for a list of tuples from the user. This article will explore different methods to take a list of tuples
3 min read