Nested Loops in Python with Example

Nested loops in Python mean one loop inside another loop. Like nested if, Python allows us to place one loop inside another loop.

When we put one or more complete loop(s) within the body of another loop, then we call it as nested loops.

We can place many loops within a loop. But, it is advice that you do not go beyond three levels of nested loops, as it will make the program look clumsy.

In Python, we can construct a nested loop by using while, or for loop statement, or with their combinations.

Let’s understand both nested for and nested while loops one by one with the help of examples.

Nested For loops in Python


When we place a for loop inside another for loop, it is called nested for loops. A nested for loops comprises an outer for loop and one or more inner for loops.

Both for loops execute depending on its test conditional expression. Each time the outer for loop repeats its execution, the program control re-enters inside the inner for loop and starts a new execution.

That is, each time the program control will enter inside the inner for loop when the outer for loop repeats the loop. When the inner for loop completes its execution, then it ends and then the outer for loop ends.

Syntax for Nested For Loop Statement


The general syntax for using nested for loops in Python is as follows:

# Outer for loop
for iterating_var in sequence:
    statement-1 # Outer block statement.
# Inner for loop
    for iterating_var in sequence:
         statement-2 # Inner block statement.
    statement-3 # Outer block statement.
statement-4


Let’s understand the working of nested for loop with the help of an example. Consider the following example code below.

# Outer for loop.
for x in 1, 2:
    print('Value of x = ',x) # It will execute two times.
  # Inner for loop.
    for y in 1, 2:
        print('Value of y = ',y) # It will execute four times.
print('Nested loops ends here...')
Output:
      Value of x =  1
      Value of y =  1
      Value of y =  2
      Value of x =  2
      Value of y =  1
      Value of y =  2
      Nested loops ends here...

a) In this example, the execution will start from the outer for loop. Python first assigns the value 1 to the iteration variable x and prints the value of x on the console.

b) Now, the program control enters the inner for loop. During the first iteration, Python assigns the value 1 to the iteration variable y and prints the value of y on the console.

Similarly, for the second iteration, Python assigns the value 2 for the iteration variable y and prints the value of y.

c) After the complete iteration of the inner loop, Python assigns the value 2 to the iteration variable x and prints the value of x on the console.

d) Then, the program control enters to the inner loop for the second iteration. Now, Python starts the iteration by assigning the value 1 to the iteration variable y and prints the value of y on the console.

e) Similarly, Python assigns the value 2 to the iteration variable y and displays the value of y.

Thus, the values of x and y will change like this:

  • When x = 1, y = 1, 2
  • When x = 2, y = 1, 2

In the above sequence, the outer for loop will execute a total 2 times, and the statement inside the loop body will execute 2 times. But, the inner for loop will execute 2 times for each x value and hence the statement inside the loop body will execute 4 times.

Nested While loops in Python


Like nested for loop, when we place a while loop inside another while loop body, then we call it as a nested while loop statement. The general syntax for a nested while loop statement in Python programming language is as below:

while test_condition-1: # Outer while loop
    statement(s)
    while test_condition-2: # Inner while loop
        statement(s)
    statement(s)
statement(s)

Python also allows us we can also nest a while loop inside a for loop and vice versa. Let’s understand the nested while loop statement with the help of a simple example program.

x = 1 # Initialization for outer while loop.
y = 1 # Intialization for the inner while loop.
# Outer while loop.
while x < 3:
    print('Outer while loop') # This statement will execute two times.
  # Inner while loop.
    while y < 3:
        print('Inner while loop') # This statement will execute two times for the first outer loop.
        y = y + 1
    x = x + 1
print('Nested while loops end here...')
Output:
      Outer while loop
      Inner while loop
      Inner while loop
      Outer while loop
      Nested while loops end here...

a) In this example, initially, the counter variable x and y set with the value 1.

b) Python first evaluates the outer while loop condition x < 3 to true. Since the condition x < 3 is true, the statement inside the outer while loop executes.

c) The program control enters to the inner while loop and checks the condition y < 3. Since it is true, the statement inside the inner while loop executes. Then, the value of y increments by 1.

d) Now Python again checks the condition y < 3. Since the value of y is less than 3, the statement inside the inner for loop again executes. Then, the value of y again increments by 1.

e) Since the inner while loop condition is now false, the program control comes outside the inner while loop, and increments the value of x by 1.

f) Now, Python again evaluates the outer while loop condition x < 3 to true. Since it is true, the statement inside the outer while loop again executes. But, the program control does not enter the inner while loop statement because the condition y < 3 is false.

g) Once the Python evaluates the outer while loop condition to false, the program control comes outside the outer while loop and executes the next statement that follows it.

Flowchart Diagram of Nested loops


The general flowchart for nested loops in Python has shown in the below figure.

Python nested loops flowchart diagram

As you can see in the flowchart diagram of nested loops, when the outer loop condition is true, the program control enters to the inner loop and checks the condition.

If the inner loop condition evaluates to true, the block of statements inside the inner loop executes. If the inner loop condition evaluates to false, the program control goes to execute the statements inside the outer loop body.

After the complete execution of the outer loop body, the outer loop condition again checked. This process continues until the outer loop condition is false.

Example Program based on Nested loops


Example 1:

Let’s write a program in Python to print a table of 2 using nested for loops.

# Outer for loop.
print('Math table of 2: ')
for x in range(2, 3): # This loop will only repeat 1 time.
    for y in range(1, 11): # Inner for loop will repeat 10 times.
        t = x * y
        print(x,'*',y,'=',t)
    print()
print('Nested for loops ends here...')
Output:
      Math table of 2: 
      2 * 1 = 2
      2 * 2 = 4
      2 * 3 = 6
      2 * 4 = 8
      2 * 5 = 10
      2 * 6 = 12
      2 * 7 = 14
      2 * 8 = 16
      2 * 9 = 18
      2 * 10 = 20
      Nested for loops ends here...

Example 2:

Let’s write a program in Python to display the tables from 1 to 5 using nested while loop.

x = 1
while x <= 5: # Outer while loop.
    t, y = 1, 1
    print()
    print('Math table for',x,':')
    while y <= 10: # Inner while loop.
        t = x * y
        print(x,'*',y,'=',t)
        y = y + 1
    x = x + 1
print('Nested while loops ends here...')

When you will run the above code, you will get tables from 1 to 5 on the console.

Example 3:

Let’s write a program in Python to print multiplication tables from 1 to 5 using nested for loop.

# Outer for loop.
print('Multiplication tables from 1 to 5: ')
for x in range(1, 6):
    for y in range(1, 11): # Inner for loop.
        t = x * y
        print(t, end=' ')
    print()
print('Nested for loops ends here...')
Output:
      Multiplication tables from 1 to 5: 
      1 2 3 4 5 6 7 8 9 10 
      2 4 6 8 10 12 14 16 18 20 
      3 6 9 12 15 18 21 24 27 30 
      4 8 12 16 20 24 28 32 36 40 
      5 10 15 20 25 30 35 40 45 50 
      Nested for loops ends here...

In this example, we have used end=’ ‘ in the print function that adds a space instead of default newline. Hence, the numbers will look in one row. The last print() function will execute at the end of the inner for loop.


Example 4:

Let’s write a Python program to display a triangle of * using nested for loop.

# Outer for loop.
print('Displaying a triangle of *: ')
for x in range(1, 6):
    for y in range(1, x + 1): # Inner for loop.
        print('* ',end='')
    print()
print('Loops end here...')
Output:
      Displaying a triangle of *: 
      * 
      * * 
      * * * 
      * * * * 
      Loops end here...

Example 5:

Let’s write a Python program to display a triangle of numbers.

# Outer for loop.
print('Displaying a triangle of numbers: ')
for x in range(1, 6):
    for y in range(1, x + 1): # Inner for loop.
        print(y,' ',end='')
    print()
print('Loops end here...')
Output:
      Displaying a triangle of numbers: 
      1  
      1  2  
      1  2  3  
      1  2  3  4  
      1  2  3  4  5  
      Loops end here...

Example 6:

Let’s create a program in Python to display a right triangle pattern of numbers.

print('Displaying a right triangle pattern of numbers: ')
z = 1
for x in range(1, 6):
    for y in range(1, x + 1): # Inner for loop.
        print(z,' ',end='')
    z += 1
    print()
print('Loops end here...')
Output:
      Displaying a right triangle pattern of numbers: 
      1  
      2  2  
      3  3  3  
      4  4  4  4  
      5  5  5  5  5  
      Loops end here...

Example 7:

Let’s create a program in Python to display the following number pattern.

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

# Outer for loop.
for x in range(6, 1, -1):
    for y in range(1, x): # Inner for loop.
        print(y,' ',end='')
    print()
print('Loops end here...')
Output:
      1  2  3  4  5  
      1  2  3  4  
      1  2  3  
      1  2  
      1  
      Loops end here...

Example 8:

Let’s write Python code to print the following alphabet pattern using nested for loops.

A
A B
A B C
A B C D
A B C D E

print("Displaying a right triangle of characters ")
# Outer for loop.
for x in range(65, 70):
    for y in range(65, x + 1): # Inner for loop.
        print(chr(y),' ',end='')
    print()
print('Loops end here...')
Output:
      Displaying a right triangle of characters 
      A  
      A  B  
      A  B  C  
      A  B  C  D  
      A  B  C  D  E  
      Loops end here...

Example 9:

Let’s create a Python program to display a reverse right triangle of alphabet characters pattern using nested for loops.

A B C D E
A B C D
A B C
A B
A

print("Displaying a reverse right triangle of characters ")
# Outer for loop.
for x in range(70, 65, -1):
    for y in range(65, x): # Inner for loop.
        print(chr(y),' ',end='')
    print()
print('Loops end here...')
Output:
      Displaying a reverse right triangle of characters 
      A  B  C  D  E  
      A  B  C  D  
      A  B  C  
      A  B  
      A  
      Loops end here...

Example 10:

Let us write a program in Python to evaluate the power series using nested while for loops. The series looks as:

S = 1 + x + x²/2! + x³/3! . . . . + xn/n! where 0 < x <1.

# Python program to find the sum of series.
import math # Using this module, we will call pow() function.
x = int(input('Enter the value of x: '))
n = int(input('Enter the value of n: '))
S = 1.0 + x
term = 1
count = 1
while count <= n: # Outer while loop.
    power = math.pow(x, count)
    fact = 1
    for i in range(1, count + 1): # Inner for loop.
        fact = fact * 1
    S = S + (power/count)
    count = count + 1
print('Sum of the series = %.2f'%S)
Output:
      Enter the value of x: 3
      Enter the value of n: 5
      Sum of the series = 89.35

In this tutorial, you have learned about nested loops in Python with various example programs. I hope that you will have understood the basic key points of nested loops and practiced all example programs. Stay tuned with the next tutorial where you will understand Infinite loop in Python and how to stop it.
Thanks for reading!!!