Sometimes, one loop isn't enough. When we need to repeat a loop inside another loop, we use a nested loop.
Think of it like this: for every student in a class, you might want to check every subject they have. The outer loop handles the students, while the inner loop handles the subjects.
What is a Nested Loop?
A nested loop is simply a loop placed inside another loop.
Python allows us to put a for loop inside a for loop, a while loop inside a while loop, or even mix them.
Basic Syntax
for outer in sequence:
for inner in sequence:
# code to executeThe outer loop runs once, and during each of its iterations, the inner loop runs completely.
Simple Example
for i in range(3):
for j in range(2):
print(i, j)Output:
0 0
0 1
1 0
1 1
2 0
2 1Here's what's happening:
i = 0→ inner loop runs forj = 0, 1i = 1→ inner loop runs again forj = 0, 1i = 2→ inner loop runs again forj = 0, 1
So, the inner loop runs 2 times for each iteration of the outer loop.
Total executions:
3 × 2 = 6Nested Loops with for
The most common use of nested loops is working with multiple sets of data.
For example:
colors = ["Red", "Blue"]
sizes = ["Small", "Large"]
for color in colors:
for size in sizes:
print(color, size)Output:
Red Small
Red Large
Blue Small
Blue LargeFor every color, Python checks every size.
Creating Patterns
Nested loops are commonly used to create patterns.
Square Pattern
for i in range(3):
for j in range(4):
print("*", end=" ")
print()Output:
* * * *
* * * *
* * * *The outer loop controls the rows, while the inner loop controls the columns.
Triangle Pattern
for i in range(1, 5):
for j in range(i):
print("*", end=" ")
print()Output:
*
* *
* * *
* * * *This is one of the most common beginner examples of nested loops.
Nested while Loops
Nested loops aren't limited to for loops. We can also nest while loops.
i = 1
while i <= 3:
j = 1
while j <= 2:
print(i, j)
j += 1
i += 1Output:
1 1
1 2
2 1
2 2
3 1
3 2Just remember that both loops need their variables updated properly. Otherwise, you can accidentally create an infinite loop.
break in Nested Loops
An important thing to understand is that break only stops the loop it is directly inside.
for i in range(3):
for j in range(3):
if j == 1:
break
print(i, j)Output:
0 0
1 0
2 0Here, break stops the inner loop when j becomes 1. The outer loop continues normally.
continue in Nested Loops
Similarly, continue affects the loop where it is written.
for i in range(2):
for j in range(3):
if j == 1:
continue
print(i, j)Output:
0 0
0 2
1 0
1 2When j == 1, that particular inner-loop iteration is skipped.
Nested Loops with Lists
Nested loops are very useful when working with nested lists, such as a matrix.
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 9The outer loop gets each row, while the inner loop gets each value inside that row.
How Many Times Does a Nested Loop Run?
This is an important concept.
for i in range(4):
for j in range(3):
print(i, j)The outer loop runs 4 times, and the inner loop runs 3 times for every outer iteration.
So:
4 × 3 = 12The print() statement runs 12 times.
For larger nested loops, this can become expensive because the number of operations grows quickly.
When Are Nested Loops Used?
Nested loops are especially useful for:
Use Case | Example |
|---|---|
Patterns | Printing stars and numbers |
Matrices | Processing rows and columns |
2D lists | Reading nested lists |
Combinations | Checking every possible pair |
Tables | Creating multiplication tables |
Games | Working with grids or boards |
For example, a multiplication table can be created using:
for i in range(1, 4):
for j in range(1, 4):
print(i * j, end=" ")
print()Output:
1 2 3
2 4 6
3 6 9Final Takeaway
A nested loop is a loop inside another loop. The outer loop controls the bigger repetition, while the inner loop performs its own complete repetition for every outer iteration.
The main thing to remember is:
For every one iteration of the outer loop, the inner loop runs from beginning to end.
Once you understand this idea, patterns, matrices, grids, and many other programming problems become much easier to handle.