Nested Loops in Python

Posted in /  

Nested Loops in Python
vinaykhatri

Vinay Khatri
Last updated on November 21, 2024

    In Python, if we define a loop inside the loop, that loop will be called the nested loop. In this Python tutorial, we will learn how to define nested loops in Python and how loop control statements work with nested loops. So let's get started.

    What are nested loops in Python?

    In Python, to create loops, we only have two keywords for and while , which are also known as for loop and while loop. To create a nested loop, we can define a loop inside a loop. For example, we can define a for loop inside a while loop, a while loop inside a for loop, a for loop inside a for loop, or a while loop inside a while loop.

    In the nested loop, the first loop is known as the outer loop, and the nested loop is known as the inner loop. If both the loops outer and inner have the iteration range of N, then the total number of times the loops will be executed is N 2 times. Nested loops are generally used when we work with multidimensional arrays and multi-structural data structures.

    How to create a Nested for loop in Python?

    Python for loop is not just a loop but also an iterator. Using a for loop in Python, we can iterate over iterable objects like string, list, tuple, dictionary, set, etc. To create a nested for loop in Python, we can define a for loop inside a for loop.

    Syntax

    The syntax for creating a nested for loop in Python is as follows:

    #outer loop
    for i in sequence1:
        #outer loop body
        #inner loop
        for j in sequence2:
            #inner loop body
    

    In the above example, you can see that the inner loop j is inside the body of the outer loop i , making it a nested for loop. Now let's discuss some examples of nested for loops.

    Example 1

    In our first example, we will use the nested for loop to create a 3X3 matrix in Python. We will take the help of a nested for loop to accept the data for all the rows and columns and use another nested for loop to print that matrix.

    Algorithm

    • Initialize an empty list matrix .
    • Create an outer loop row from range 0 to 3, representing the row of 3 x3 matrix.
    • Inside the outer loop create an empty list r , that will hold the values for each row.
    • Inside the outer loop, create an inner loop col from range 0 to 3, defining 3 columns for each row 3X 3 .
    • In the body of the inner for loop asks the user to enter the values for the matrix and append them to the empty list r .
    • Outside the inner for loop append the r list to the empty list matrix .
    • Now to print the matrix we can either use the print statement directly or use a nested loop structure to print the items in a pattern.
    #initialize an empty matrix
    matrix = []
    
    #the 3 rows
    for row in range(3):
        #empty row list that will hold the data for each row
        r= []
        
        #nested loop for 
        #the 3 coloums data
        for col in range(3):
            data = int(input(f"Input the data for {row+1}x{col+1}: "))
            
            #add the column data to r
            r.append(data)
        #add the row to the matix    
        matrix.append(r)
    
    #print the matrix data using nested for loop
    print("\nThe 3X3 Matrix you entered is:")
    for row in range(3):
        for col in range(3):
            print(matrix[row][col], end=" ")
        print()
    

    Output

    Input the data for 1x1: 1
    Input the data for 1x2: 2
    Input the data for 1x3: 3
    Input the data for 2x1: 4
    Input the data for 2x2: 5
    Input the data for 2x3: 6
    Input the data for 3x1: 7
    Input the data for 3x2: 8
    Input the data for 3x3: 9
    
    The 3X3 Matrix you entered is:
    1 2 3 
    4 5 6 
    7 8 9

    In the above program, we first run the nested for loop to accept the matrix elements. And in the second nested for loop, we print those elements. In both nested for loops the outer and inner for loops has the range of 3, making it a 3X3 = 9 times of the inner body execution.

    Example 2

    The nested for loops are often used with the range functions to print star patterns or pyramids. Let's print the following pattern with a nested for loop in Python.

    *****
     ****
      ***
       **
        *

    To print the following pattern , we need two inner loops inside the outer loop. With the first inner loop, we will print the white spaces " " and with the second inner loop star "*".

    #outer loop i
    for i in range(5):
        #first inner loop for stars
        for k in range(0,i):
            print(" ",end="")
            
        #second inner loop for star
        for j in range(i,5):
            print("*", end="")
        print()
    

    Nested while loop inside a for loop

    Similar to the nested for loop, we can define a nested while loop inside a for loop. The concept of nested while loop is the same as nested for loop. Let's Implement the

    Example 1 of the above section uses a while loop inside a for a loop.

    #initialize an empty matrix
    matrix = []
    
    #the 3 rows
    for row in range(3):
        #empty row list that will hold the data for each row
        r= []
    
        col =0
        #nested loop for 
        #the 3 coloums data
        while col<3:
            data = int(input(f"Input the data for {row+1}x{col+1}: "))
            
            #add the column data to r
            r.append(data)
    
            #increase the col value
            col+=1
            
        #add the row to the matix    
        matrix.append(r)
    
    #print the matrix data using nested for loop
    print("\nThe 3X3 Matrix you entered is:")
    print(matrix)
    

    Output

    Input the data for 1x1: 4
    Input the data for 1x2: 4
    Input the data for 1x3: 4
    Input the data for 2x1: 5
    Input the data for 2x2: 5
    Input the data for 2x3: 5
    Input the data for 3x1: 6
    Input the data for 3x2: 6
    Input the data for 3x3: 6
    
    The 3X3 Matrix you entered is:
    [[4, 4, 4], [5, 5, 5], [6, 6, 6]]

    In this example, we used the while loop inside the for loop to accept the column data from the user.

    Example 2: Create the following rectangular pattern using the nested while loop in Python.

    **********
    **********
    **********

    Rectangle pattern in Python using nested while loop

    rows = 0
    while rows<3:
        columns = 0
        while columns < 10:
            print("*", end="")
            #increment the value of columns
            columns+=1
    
            
        #print a new line
        print()
    
        #increment the value of rows
        rows+=1
    

    Nested Loop Control Statements

    There are two loop control statements in Python

    1. break
    2. continue

    Python break in nested loop

    The break is a reserved keyword in Python. It is used inside a loop body and terminates the loop execution or iteration. The break keyword-only terminates that loop in which native body it is defined. For instance, if the loop is nested and the break keyword is inside the inner loop, the inner loop will be terminated. If the break is in the outer loop, it will terminate the outer loop.

    Example 1 break inside the inner loop

    for i in range(3):
        print("Outer Loop:", i)
        for j in range(3):
            if j==i:
                #when i=0 &j=0,i=1 & j=1,  and i=2&j=2 break the inner loop
                break
            else:
                print("\tInner Loop:", j)
    

    Output

    Outer Loop: 0
    Outer Loop: 1
    	Inner Loop: 0
    Outer Loop: 2
    	Inner Loop: 0
    	Inner Loop: 1

    In this example, you can see that the outer loop executes 3 times, and the inner loop stops running after i==j . This is because when Python parses the break statement inside the inner loop j, it terminates the inner loop's execution.

    Example 2 break outside the inner loop inside the outer body

    for i in range(3):
        print("Outer Loop:", i)
        for j in range(3):
            print("\tInner Loop:", j)
    
        break 
    

    Output

    Outer Loop: 0
    	Inner Loop: 0
    	Inner Loop: 1
    	Inner Loop: 2

    In the example, the break statement is defined in the outer loop body. When Python read that break statement, it terminates the outer loop i and stop its further execution.

    Python continue in a nested loop

    continue is another loop control keyword. It can skip the loop iteration and directly jump to the next iteration without executing the loop body code written after it. Similar to the break keyword, the continue will only affect that loop statement where it is defined. If it is present in the inner loop body, it will only affect the inner loop,  and if it is present in the outer loop, it will affect the outer loop.

    Example 1 continue inside the inner loop

    for i in range(3):
        print("Outer Loop:", i)
        for j in range(3):
            if i==j:
                continue
            print("\tInner Loop:", j)

    Output

    Outer Loop: 0
    	Inner Loop: 1
    	Inner Loop: 2
    Outer Loop: 1
    	Inner Loop: 0
    	Inner Loop: 2
    Outer Loop: 2
    	Inner Loop: 0
    	Inner Loop: 1

    In the above example, the continue statement skips the inner loop execution when i , and j values were the same.

    Example 2 continue inside the outer loop and outside the inner loop

    for i in range(3):
        if i==1:
            continue
        print("Outer Loop:", i)
        for j in range(3):
            if i==j:
                continue
            print("\tInner Loop:", j)     
    

    Output

    Outer Loop: 0
    	Inner Loop: 1
    	Inner Loop: 2
    Outer Loop: 2
    	Inner Loop: 0
    	Inner Loop: 1
    

    In this example, the continue statement skips the outer loop iteration when the i value was 1 .

    How to use list comprehension to write a nested loop in a single line

    List comprehension is a shorthand technique in Python to create a list using for loop using a single-line statement. We can use the list comprehension technique and create a matrix using a single-line statement.

    Example nested loop in the list comprehension.

    array = [[i,j] for i in range(3) for j in range(3) if i!=j]
    
    print(array)

    Output

    [[0, 1], [0, 2], [1, 0], [1, 2], [2, 0], [2, 1]]

    The above single-line list comprehension code is equivalent to the following code

    array=[]
    
    for i in range(3):
        for j in range(3):
            if i!=j:
                array.append([i,j])

    The list comprehension saves us time and lines of code.

    Nested while loop in Python

    We generally use while loop in Python when we are not certain about the number of times a code statement should be executed. The while loop executes a code repeatedly until the condition becomes False or it encounters the break statement. When we define a while loop inside a while loop, it is called a nested while loop.

    nested while loop syntax in Python

    while expression:
        #outer while loop body
        while expression:
            #inner while loop body

    Example

    Let's see an example and implement a nested while loop in Python. Write a script in Python that prints the first 10 even numbers 5 times.

    times = 0
    #outer loop to execute the inner loop 5 times
    while times<5:
        even = 2
        #inner loop print the first 10 even numbers
        while even<=20:
            print(even, end=" ")
            #increment the value of even
            even+=2
        #new line
        print()
        #increment the value of times
        times+=1
    

    Output

    2 4 6 8 10 12 14 16 18 20 
    2 4 6 8 10 12 14 16 18 20 
    2 4 6 8 10 12 14 16 18 20 
    2 4 6 8 10 12 14 16 18 20 
    2 4 6 8 10 12 14 16 18 20

    When should we nested loops in Python?

    Nested loops come in handy when iterating over the matrix and nested data structures, including complex algorithms such as sorting and searching. The nested loop allows us to go deep into data structures, but it comes with a price. Putting a single-layer nested loop increases the time complexity of a program to O(N 2 ).

    Alternative of Nested loops

    In data structures like graphs and trees, where to go deep into the branches, we may require n nested loops. In such cases, Recursion provides a better alternative to the nested for or while loop.

    Conclusion

    When we define a loop inside the body of another loop, it is called the nested loop in Python. To create a nested loop, we have two loop statements for loop and while loop, we can either define for loop inside a for loop or while loop inside a while loop or mix them and create a nested loop statement. Many important sorting algorithms use the nested loop to sort the data values present in an array or list.

    People are also reading:

    FAQs


    When we define a loop inside a loop, it is called nested a nested loop.

    The break statement is a Python loop control statement that can terminate the execution of a loop statement.

    No, if we use the break keyword outside the loop body, Python raises the Syntax Error 'break' outside loop.

    The time complexity will remain O(N2). This is because the inner loops are at the same level, and their combined time complexity will be linear. If the 2nd inner loop is inside the first inner loop, then the time complexity of the program will raise to O(N2).

    Leave a Comment on this Post

    0 Comments