Python Nested Loops

Nested Loop

A nested loop is a loop inside another loop. The “inner loop” will be executed one time for each iteration of the “outer loop”.

If outer loop executes M times and inner loop executes N times , the time complexity of the loop will be (M*N).

A final note on loop nesting is that we can put any type of loop inside of any other type of loop. For example a for loop can be inside a while loop or vice versa

nested loop in python

Syntax : 

  • For/while (Outer Loop):
    • For/while( Inner Loop) :
  • For/while ( Outer Loop) :
    • if and else ( Inner Loop)r

Working :

  • The outer loop iterates through the range from 0 to n/len(sequence) and for each item in that sequence.
  • It enters the inner loop where it iterates over a range of that item.
  • For each iteration of that item, it perform the given operation.
  • It only leaves the inner loop when it has completely iterated through a range of that item.
  • When it leaves the inner loop, it goes back to the outer loop and the process continues until it has completely iterated over its sequence.
use of nested loop in python

Example :

#python Program 
#nested Loop

#for-for nested Loop 
for i in range(1,3):
    for j in range(1,6): #print the multiplication of 1 and 2 
        print(i*j,end=‘ ‘)
    print(‘ ‘

#for-while nested loop
j=1 
for i in range(1,3):
    j=1
    while(j<6): 
        print(i*j, end =‘ ‘)

        j=j+1 
    print(‘ ‘

#while-while nested loop 
i=1
while(i<3):
    j=1 
    while(j<6):
        print(i*j,end=‘ ‘)
        j=j+1 
    print(‘ ‘)
    i+=1 

#while-If nested Loop 
i=1 
j=1 
while(i<3):
    if(j<6):
        print(i*j, end =‘ ‘)
        j=j+1  
    else:
        j=1 
        i+=1
        print()



Output:

1 2 3 4 5
2 4 6 8 10
1 2 3 4 5
2 4 6 8 10
1 2 3 4 5
2 4 6 8 10
1 2 3 4 5
2 4 6 8 10