Nested Loop in Python

A nested loop is simply a loop inside another loop which allows you to repeat actions in a structured way. For example, if you want to print combinations of numbers ([1, 1], [1, 2], [1, 3], [2, 1], [2, 2], [2, 3], [3, 3]...), the outer loop runs first, and for each iteration, the inner loop runs completely. Loops are important because they help you repeat similar actions without writing same code again and again. Nested loops are especially useful in real-life applications like in working with 2d data structures like matrix, which lookslike a table of rows and columns. They also used in algorithms, (many algorithms use nested loops sorting a list of items or finding combinations) which help you to solve complex problems.

Nested Loop in Python
Nested Loop in Python

Basics of Loops

Before moving on to the nested loops, let’s brushup the basic loops in Python.

  • for loop in Python is used to repeat a block of code a specific number of times.
  • while loop runs as long as a certain condition is True.
  • Jump Statements are used to control the flow of a loop.
    • break: This stops the loop completely.
    • continue: This skips the current iteration and moves to the next iteration in the loop.
    • pass: This does nothing and is used as a placeholder only.

What is Nested Loop?

A nested loop means a loop inside another loop. You can think of it like a clock:

  • The hour hand moves slowly (outer loop).
  • The minute hand moves faster (inner loop).

For every hour (outer loop), the minute hand goes from 0 to 59 (inner loop runs many times).

In Python, nested loops allow us to repeat actions inside another repeating action. This is helpful when we are working with tables (2D arrays), patterns, or combinations.

Example of a Nested Loop

So, let’s see how nested loop works with an example:

for i in range(3):  # Outer loop
    for j in range(3):  # Inner loop
        print(i, j)
Python
  • The outer loop runs first (i takes values from 0 to 2).
  • Inside each outer loop run, the inner loop runs completely (j takes values from 0 to 2).
  • The print(i, j) line executes every time the inner loop runs.

Let’s see how this nested loop works step by step.

Step 1: Outer Loop Starts
  • Outer loop runs for i = 0, then it’s indented code block runs which is another for loop.
Step 2: Complete the Inner Loop for i = 0
  • The inner loop run 3 times:
    • When j = 0, it print 0, 0.
    • When j = 1, it print 0, 1.
    • When j = 2, it print 0, 2.
  • The inner loop is done.
Step 3: Move to the Next Value of i (i = 1)
  • Now, it move to the outer loop again for the next value of i which is 1 and start the inner loop again.
Step 4: Complete the Inner Loop for i = 1
  • The inner loop runs again:
    • When j = 0, it print 1, 0.
    • When j = 1, it print 1, 1.
    • When j = 2, it print 1, 2.
  • The inner loop finished again.
Step 5: Move to the Last Value of i (i = 2)
  • Now, it set i to 2 and run the inner loop last time.
Step 6: Complete the Inner Loop for i = 2
  • The inner loop runs for the last time:
    • When j = 0, it print 2, 0.
    • When j = 1, it print 2, 1.
    • When j = 2, it print 2, 2.
  • The inner loop is done.
Step 7: End of the Outer Loop
  • There are no more values for i to take.
  • Both loops have finished running.

Output:

0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Bash

In this process, the outer loop runs three times (for i = 01, and 2). For each iteration or each value of i, the inner loop runs three times (for j = 01, and 2). This is why we get a total of 9 outputs (3 * 3 = 9).

Indentation and Code Block Scope

When you work with nested loops, you need to be careful of indentation. If the indentation is not correct, you may get unexpected results.

For example:

for i in range(3):
print(i)  # Error: This line is not indented
Python

Python will throw an SyntaxError because it expects an indented block after : of for loop.

Another example:

for i in range(2):  
    for j in range(2):  
        print(i, j)  # Inside both loops  
    print("End of inner loop")  # Only inside the outer loop  

# Output:
# 0 0
# 0 1
# End of inner loop
# 1 0
# 1 1
# End of inner loop
Python

In nested loops, indentation helps separate inner and outer loops. So, here "End of inner loop" prints after the inner loop completes but inside the outer loop.

Nested while loops

While loops are also used in nested loops.

For example:

i = 0
while i < 3:  # Outer loop
    j = 0
    while j < 3:  # Inner loop
        print(i, j)
        j += 1  # Increment inner loop counter
    i += 1  # Increment outer loop counter

# Output:
# 0 0
# 0 1
# 0 2
# 1 0
# 1 1
# 1 2
# 2 0
# 2 1
# 2 2
Python

It works similarly to a nested for loop, but instead of running a fixed number of times, it continues until a condition becomes false.

You can also combine for loops and while loops in your code.

For example:

for i in range(3):
    print(f"For loop iteration: {i}")
    
    j = 0
    while j < 2:
        print(f"  While loop iteration: {j}")
        j += 1
Python

Conclusion

In conclusion, I want to say that nested loops are really important. I would say that they serve as a gateway or cutoff point for understanding any programming language. If you deeply understand this concept and operator precedence and associativity, then you can continue in programming without much difficulty in future topics. But we are not finished yet. We still have a lot of related problems to solve, like working with 2D arrays and printing star patterns which we will cover in the next blog.

Nested Loop in Python

Break stops inner loop early

1 / 7

What will be the output of the following code?

for i in range(3):
for j in range(3):
if i == j:
break
print(i, j)

Multiply loop counts

2 / 7

How many times will the following code print output?

for i in range(2):
for j in range(3):
print(i.j)

Multiply loop iterations

3 / 7

How many times does the following code print “Python”?

for i in range(2):
for j in range(2):
for k in range(2):
print("Python")

Inner loop inside outer loop

4 / 7

What is a nested loop?

Loops can be combined

5 / 7

What happens if you mix a for loop with a while loop?

Inner loop runs fully each time

6 / 7

What is the output of the following while loop?

for i in range(3):
for j in range(3):
if i == j:
break
print(i, j)

                            

Python follows indentation rules

7 / 7

What will happen if the indentation of the inner loop is incorrect?

Your score is

The average score is 0%

0%

Leave a Reply

Your email address will not be published. Required fields are marked *