In the previous lessons, you learned how to use the Python for loop and while loop to repeat a block of code multiple times. You also learned how the break, continue, and pass statements control loop execution.
However, many programming problems require one loop to execute completely before another loop continues. Examples include printing patterns, generating multiplication tables, processing rows and columns of data, and working with two-dimensional structures such as matrices.
To solve these problems, Python allows you to place one loop inside another loop. This is called a nested loop.
A nested loop is simply a loop inside another loop. The outer loop controls how many times the inner loop executes, while the inner loop completes all of its iterations for every iteration of the outer loop.
After completing this lesson, you will be able to:
for loops.while loops.for loop inside a while loop.while loop inside a for loop.A nested loop is a loop placed inside another loop.
The loop that contains another loop is called the outer loop, while the loop inside it is called the inner loop.
During execution, every iteration of the outer loop causes the inner loop to execute completely.
This allows a program to perform repeated operations within repeated operations.
Nested loops are useful whenever data is organized into rows and columns or when one repetitive task depends on another.
Some common uses include:
for Loopfor outer_variable in sequence:
for inner_variable in sequence:
statements
The inner loop executes completely for each iteration of the outer loop.
while Loopwhile condition1:
while condition2:
statements
The inner while loop repeats until its condition becomes false before the outer loop continues.
for LoopsThe most common type of nested loop is a for loop inside another for loop.
for row in range(1, 4):
for column in range(1, 4):
print(row, column)
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Notice that the inner loop runs three times for every single iteration of the outer loop.
while LoopsNested while loops work in exactly the same way.
row = 1
while row <= 3:
column = 1
while column <= 3:
print(row, column)
column += 1
row += 1
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Before every iteration of the outer loop, the inner loop variable is initialized again.
for Loop Inside a while LoopPython also allows different types of loops to be combined.
row = 1
while row <= 3:
for column in range(1, 4):
print(row, column)
row += 1
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
The for loop executes completely before the while loop proceeds to the next iteration.
while Loop Inside a for LoopA while loop can also be placed inside a for loop.
for row in range(1, 4):
column = 1
while column <= 3:
print(row, column)
column += 1
Output
1 1
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
This demonstrates that nested loops are not limited to loops of the same type.
Understanding the execution order is important.
Consider the following program.
for i in range(1, 3):
for j in range(1, 4):
print(i, j)
Execution Steps
i = 1.j = 1.1 1.j = 2.j = 3.i = 2.Output
1 1
1 2
1 3
2 1
2 2
2 3
The total number of executions depends on both loops.
The formula is:
Total Iterations =
Outer Loop Iterations × Inner Loop Iterations
Example:
Outer Loop = 4
Inner Loop = 5
Total executions:
4 × 5 = 20
This is why deeply nested loops can become slower when working with large amounts of data.
In this section, you learned what Python nested loops are and why they are useful. You explored nested for loops, nested while loops, and combinations of for and while loops. You also learned the syntax of nested loops, followed their execution flow step by step, and understood how the total number of iterations is calculated. In the next section, you will learn how nested loops are used for pattern printing, multiplication tables, working with lists, strings, dictionaries, and the range() function, along with common beginner mistakes and best practices.
In the previous section, you learned what nested loops are and how they execute. In this section, you will explore some of the most common applications of nested loops, including pattern printing, multiplication tables, working with lists, strings, dictionaries, and the range() function. You will also learn common beginner mistakes and coding best practices.
One of the most popular uses of nested loops is printing patterns. The outer loop controls the number of rows, while the inner loop controls the number of columns or symbols printed in each row.
for row in range(5):
for column in range(5):
print("*", end=" ")
print()
Output
* * * * *
* * * * *
* * * * *
* * * * *
* * * * *
The outer loop creates five rows, and the inner loop prints five stars in each row.
for row in range(1, 6):
for column in range(row):
print("*", end=" ")
print()
Output
*
* *
* * *
* * * *
* * * * *
The number of stars increases with each row.
Nested loops are useful for creating multiplication tables.
for i in range(1, 6):
for j in range(1, 6):
print(i * j, end="\t")
print()
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
Each row represents one multiplication table.
Nested loops can process lists that contain other lists.
students = [
["Rahul", 85],
["Amit", 92],
["Neha", 88]
]
for student in students:
for value in student:
print(value, end=" ")
print()
Output
Rahul 85
Amit 92
Neha 88
The outer loop processes each student, while the inner loop processes the values inside each student record.
Nested loops can also work with strings.
words = ["Python", "Java"]
for word in words:
for letter in word:
print(letter, end=" ")
print()
Output
P y t h o n
J a v a
The outer loop selects a word, and the inner loop prints each character.
Dictionaries can also be processed using nested loops.
students = {
"Rahul": {
"Age": 20,
"Marks": 85
},
"Neha": {
"Age": 21,
"Marks": 92
}
}
for name, details in students.items():
print(name)
for key, value in details.items():
print(key, ":", value)
print()
Output
Rahul
Age : 20
Marks : 85
Neha
Age : 21
Marks : 92
The outer loop processes each student, while the inner loop processes the details for that student.
range() FunctionThe range() function is commonly used with nested loops to generate rows and columns.
for row in range(1, 4):
for column in range(1, 5):
print("(", row, ",", column, ")", end=" ")
print()
Output
(1,1) (1,2) (1,3) (1,4)
(2,1) (2,2) (2,3) (2,4)
(3,1) (3,2) (3,3) (3,4)
This technique is widely used when working with grids and matrices.
Consider the following program.
for row in range(1, 3):
for column in range(1, 4):
print(row, column)
print("Row Completed")
Execution Steps
row = 1.1 1, 1 2, and 1 3.row = 2.Output
1 1
1 2
1 3
Row Completed
2 1
2 2
2 3
Row Completed
for i in range(3):
for j in range(3):
print(i, j)
This results in an IndentationError.
while LoopsAlways reinitialize the inner loop variable before each outer loop iteration.
Deeply nested loops can make programs difficult to read and may reduce performance.
Remember that the outer loop controls the number of times the inner loop executes.
Avoid changing the size of a list or dictionary while iterating through it.
row and column.In this section, you learned how nested loops are used for pattern printing, multiplication tables, processing lists, strings, dictionaries, and working with the range() function. You also explored the execution flow of nested loops, reviewed common beginner mistakes, and learned coding best practices for writing clear and efficient nested loop programs. In the next section, you will apply these concepts by building practical programs such as rectangle and pyramid patterns, multiplication matrices, student marks tables, matrix traversal, and chessboard patterns.
Nested loops are commonly used in real-world Python programs where one repetitive task depends on another. They are especially useful for pattern printing, working with tables, processing matrices, displaying rows and columns, and solving two-dimensional problems.
In this section, you will build practical programs using nested loops. These examples will help you understand how nested loops work in different programming situations.
The following program prints a rectangle of stars using nested for loops.
rows = 4
columns = 6
for row in range(rows):
for column in range(columns):
print("*", end=" ")
print()
Output
* * * * * *
* * * * * *
* * * * * *
* * * * * *
The outer loop controls the number of rows, while the inner loop prints the stars in each row.
The following program prints a right-angled pyramid.
for row in range(1, 6):
for column in range(row):
print("*", end=" ")
print()
Output
*
* *
* * *
* * * *
* * * * *
The number of stars increases with each row.
Nested loops make it easy to generate multiplication tables.
for row in range(1, 6):
for column in range(1, 6):
print(row * column, end="\t")
print()
Output
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
5 10 15 20 25
This program displays student names along with their marks.
students = [
["Rahul", 85],
["Neha", 92],
["Amit", 78]
]
for student in students:
for value in student:
print(value, end="\t")
print()
Output
Rahul 85
Neha 92
Amit 78
The outer loop processes each student, and the inner loop processes the details of that student.
A matrix is a list containing other lists. Nested loops allow you to process every element.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
for row in matrix:
for value in row:
print(value, end=" ")
print()
Output
1 2 3
4 5 6
7 8 9
Nested loops are commonly used when working with two-dimensional arrays and matrices.
This program prints the coordinates of a simple chessboard.
for row in range(1, 9):
for column in range(1, 9):
print("(", row, ",", column, ")", end=" ")
print()
Partial Output
(1,1) (1,2) (1,3) (1,4) ...
(2,1) (2,2) (2,3) (2,4) ...
...
(8,8)
Each coordinate represents one square on the chessboard.
The following program prints a number triangle.
for row in range(1, 6):
for column in range(1, row + 1):
print(column, end=" ")
print()
Output
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Nested loops can compare every element of one list with every element of another list.
list1 = [1, 2, 3]
list2 = [4, 5]
for value1 in list1:
for value2 in list2:
print(value1, value2)
Output
1 4
1 5
2 4
2 5
3 4
3 5
Consider the following program.
for row in range(1, 3):
for column in range(1, 4):
print(row, column)
print("Next Row")
Execution Steps
row = 1.row = 2.Output
1 1
1 2
1 3
Next Row
2 1
2 2
2 3
Next Row
Avoid unnecessary levels of nesting because they reduce readability and performance.
for row in range(5):
for column in range(5):
print(row, column)
Names such as row and column clearly describe the purpose of each loop variable.
If a problem can be solved with a single loop, avoid adding extra nesting.
Keep the code inside each loop simple and focused on one task.
Before using large datasets, test nested loops with a few rows and columns to verify the output.
while loops.In this section, you applied Python nested loops to practical programming problems such as printing rectangle and pyramid patterns, generating multiplication matrices, displaying student marks, traversing matrices, creating chessboard coordinates, printing number patterns, and comparing two lists. You also learned coding best practices, reviewed common beginner mistakes, and followed the execution flow of nested loops step by step. In the final section, you will review the complete lesson through a summary, key takeaways, frequently asked questions, coding exercises, interview questions, a mini project, and a preview of the next lesson on the Python Loop else Statement.
In this lesson, you learned how Python nested loops allow one loop to execute inside another loop. A nested loop is useful when a repetitive task must be performed within another repetitive task. The outer loop controls the number of times the inner loop executes, while the inner loop completes all of its iterations before the outer loop continues.
You explored different types of nested loops, including nested for loops, nested while loops, a for loop inside a while loop, and a while loop inside a for loop. You also learned how nested loops are commonly used for pattern printing, multiplication tables, matrices, lists, dictionaries, and other two-dimensional data structures.
Through practical examples such as rectangle patterns, pyramid patterns, multiplication matrices, student marks tables, matrix traversal, chessboard coordinates, and number patterns, you learned how nested loops solve real-world programming problems efficiently.
Understanding nested loops is an important step toward mastering more advanced programming topics such as matrices, algorithms, data processing, and game development.
for loops and nested while loops.for loop inside a while loop.row and column improve code clarity.A nested loop is a loop placed inside another loop.
The outer loop controls the overall repetitions, while the inner loop executes completely during each iteration of the outer loop.
for loop be nested inside a while loop?Yes. Python allows different loop types to be nested together.
while loop be nested inside a for loop?Yes. Both combinations are supported in Python.
Nested loops are used for pattern printing, multiplication tables, matrix processing, grid-based programs, and two-dimensional data.
The inner loop executes completely for every iteration of the outer loop.
Yes. Additional levels of nesting increase the total number of iterations and may slow programs that process very large datasets.
Use meaningful variable names, proper indentation, comments where necessary, and avoid unnecessary nesting.
for loops.while loop that prints row and column numbers.Create a Python program that generates multiplication tables from 1 to 10 using nested for loops.
Your program should:
Table of 1
1 x 1 = 1
1 x 2 = 2
...
1 x 10 = 10
Table of 2
2 x 1 = 2
2 x 2 = 4
...
2 x 10 = 20
...
Table of 10
10 x 1 = 10
10 x 2 = 20
...
10 x 10 = 100
All Multiplication Tables Generated Successfully.
Congratulations! You have mastered Python nested loops and can now solve problems involving rows and columns, pattern printing, multiplication tables, matrices, and other two-dimensional data structures. Combined with your knowledge of for loops, while loops, and loop control statements, you now have a solid understanding of Python looping concepts.
In the next lesson, you will learn the Python Loop else Statement. You will discover how the else clause works with both for and while loops, how it behaves when a loop ends normally or with a break statement, and how it can be used in search algorithms, prime number checking, and other practical programming tasks.