Python Nested Loops Examples
Example 1: Basic Example of Python Nested Loops
Python3
x = [ 1 , 2 ] y = [ 4 , 5 ] for i in x: for j in y: print (i, j) |
Output:
1 4 1 5 2 4 2 5
Python3
x = [ 1 , 2 ] y = [ 4 , 5 ] i = 0 while i < len (x) : j = 0 while j < len (y) : print (x[i] , y[j]) j = j + 1 i = i + 1 |
Time Complexity: O(n2)
Auxiliary Space: O(1)
Example 2: Printing multiplication table using Python nested for loops
Python3
# Running outer loop from 2 to 3 for i in range ( 2 , 4 ): # Printing inside the outer loop # Running inner loop from 1 to 10 for j in range ( 1 , 11 ): # Printing inside the inner loop print (i, "*" , j, "=" , i * j) # Printing inside the outer loop print () |
Output:
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 3 * 1 = 3 3 * 2 = 6 3 * 3 = 9 3 * 4 = 12 3 * 5 = 15 3 * 6 = 18 3 * 7 = 21 3 * 8 = 24 3 * 9 = 27 3 * 10 = 30
Time Complexity: O(n2)
Auxiliary Space: O(1)
In the above example what we do is take an outer for loop running from 2 to 3 for multiplication table of 2 and 3 and then inside that loop we are taking an inner for loop that will run from 1 to 10 inside that we are printing multiplication table by multiplying each iteration value of inner loop with the iteration value of outer loop as we see in the below output.
Example 3: Printing using different inner and outer nested loops
Python3
# Initialize list1 and list2 # with some strings list1 = [ 'I am ' , 'You are ' ] list2 = [ 'healthy' , 'fine' , 'geek' ] # Store length of list2 in list2_size list2_size = len (list2) # Running outer for loop to # iterate through a list1. for item in list1: # Printing outside inner loop print ( "start outer for loop " ) # Initialize counter i with 0 i = 0 # Running inner While loop to # iterate through a list2. while (i < list2_size): # Printing inside inner loop print (item, list2[i]) # Incrementing the value of i i = i + 1 # Printing outside inner loop print ( "end for loop " ) |
Output:
start outer for loop I am healthy I am fine I am geek end for loop start outer for loop You are healthy You are fine You are geek end for loop
Time Complexity: O(n2)
Auxiliary Space: O(1)
In this example, we are initializing two lists with some strings. Store the size of list2 in ‘list2_Size’ using len() function and using it in the while loop as a counter. After that run an outer for loop to iterate over list1 and inside that loop run an inner while loop to iterate over list2 using list indexing inside that we are printing each value of list2 for every value of list1.
Python Nested Loops
In Python programming language there are two types of loops which are for loop and while loop. Using these loops we can create nested loops in Python. Nested loops mean loops inside a loop. For example, while loop inside the for loop, for loop inside the for loop, etc.