Python Nested Loops

In the last lesson, we learned about the Python pass Statement. Now letโ€™s place one loop inside another to work with rows, columns, and grouped data.

๐Ÿ” Letโ€™s Talk About Loops Inside Loops

We already know about loops. A for loop or a while loop repeats something.

But what if we need to repeat something, and inside that repetition, we need to repeat something else?

That is a nested loop.

A nested loop is simply a loop inside another loop. The inner loop runs completely for each iteration of the outer loop.

Think of it like a clock. The minute hand goes around once every hour. But the hour hand moves only after the minute hand completes a full circle. That is nesting.

Or think of a school. We have classes. And in each class, we have students. To go through every student in every class, we would use a nested loop: one loop for classes, and inside it, another loop for students.

๐Ÿงช A Simple Python Nested Loop Example

Letโ€™s start with something small.

for i in range(1, 4):
for j in range(1, 4):
print(f"i={i}, j={j}")

Output

i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
i=3, j=1
i=3, j=2
i=3, j=3

Let me explain what happened.

  • The outer loop starts with i=1.
  • Inside, the inner loop runs completely: j=1, j=2, j=3. That prints three lines.
  • Then the outer loop moves to i=2.
  • The inner loop runs completely again: j=1, j=2, j=3. Three more lines.
  • Then i=3, and again the inner loop runs three times.

So the inner loop runs 3 times for each outer loop iteration. Total 9 lines.

That is the key idea: for each single step of the outer loop, the inner loop does all its steps.

๐Ÿ’ก Python Nested Loops: A Real-Life Example โ€” Multiplication Table

Letโ€™s print a multiplication table from 1 to 5.

for i in range(1, 6):
for j in range(1, 6):
print(f"{i} x {j} = {i*j}")
print("-" * 15)

Output

1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
1 x 4 = 4
1 x 5 = 5
---------------
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
---------------
... and so on

For each number i from 1 to 5, we loop through j from 1 to 5 and print the product. Then we print a separator line.

That is a classic use of nested loops.

๐Ÿ–จ๏ธ Another Example โ€” Printing Patterns

Nested loops are often used to print patterns. Letโ€™s print a triangle of stars.

rows = 5
for i in range(1, rows + 1):
for j in range(i):
print("*", end=" ")
print()

Output

*
* *
* * *
* * * *
* * * * *

Let me explain.

  • The outer loop runs from 1 to 5 (inclusive). i is the current row number.
  • For each row, the inner loop runs i times.
  • Each time, it prints a star and a space, but does not go to a new line (end=" ").
  • After the inner loop finishes, we call print() to move to the next line.

So for row 1, it prints one star. For row 2, two stars. And so on.

That is how we build patterns with nested loops.

๐Ÿ“Œ Nested while Loops in Python

We can nest while loops too. But letโ€™s be careful. It is easier to make an infinite loop.

i = 1
while i <= 3:
j = 1
while j <= 3:
print(f"i={i}, j={j}")
j += 1
i += 1

This produces the same output as the earlier for loop example.

Notice that we have to reset j = 1 inside the outer loop. If we did not, j would stay at 4 after the first outer iteration, and the inner loop would never run again.

So with nested while loops, we must initialize and update the inner loop variable carefully.

โš™๏ธ Mixing for and while in Python

We can mix them. A for loop outside, a while loop inside, or vice versa.

for i in range(1, 4):
j = 1
while j <= 3:
print(f"i={i}, j={j}")
j += 1

This works fine. But it is often simpler to stick with one type for consistency.

๐Ÿ” break and continue in Nested Loops

Letโ€™s remember that break and continue only affect the innermost loop they are in. They do not break out of the outer loop.

Letโ€™s see an example with break.

for i in range(1, 4):
for j in range(1, 4):
if j == 2:
break
print(f"i={i}, j={j}")

Output

i=1, j=1
i=2, j=1
i=3, j=1

For each i, the inner loop starts at j=1. It prints. Then j=2 triggers break. The inner loop stops. Then the outer loop goes to the next i, and the inner loop starts fresh again.

So break only stops the inner loop. The outer loop continues.

If we want to break out of both loops at once, we would need a flag variable or use a function with return. That is a bit advanced for now.

Now letโ€™s see continue.

for i in range(1, 4):
for j in range(1, 4):
if j == 2:
continue
print(f"i={i}, j={j}")

Output

i=1, j=1
i=1, j=3
i=2, j=1
i=2, j=3
i=3, j=1
i=3, j=3

When j=2, continue skips the print. Then the inner loop continues to j=3. So j=2 is skipped, but the loop goes on.

๐Ÿงญ Python Nested Loops: A Real-Life Example โ€” Seating Arrangement

Imagine a small theater with 3 rows and 4 seats per row. We want to print a seat map.

for row in range(1, 4):
for seat in range(1, 5):
print(f"R{row}S{seat}", end=" ")
print()

Output

R1S1 R1S2 R1S3 R1S4
R2S1 R2S2 R2S3 R2S4
R3S1 R3S2 R3S3 R3S4

That is a simple seat map. We could extend this to mark some seats as taken, etc.

โš ๏ธ Common Mistakes with Python Nested Loops

โŒ Mistake 1: Forgetting to Reset the Inner Loop Variable

In a while loop, if we do not reset the inner variable, it will not run properly after the first outer iteration.

i = 1
while i <= 3:
j = 1 # This must be inside the outer loop
while j <= 3:
print(i, j)
j += 1
i += 1

If we put j = 1 outside the outer loop, the inner loop will only run for the first i.

๐Ÿšซ Mistake 2: Using the Same Variable Name

Using the same variable name for both loops can cause confusion.

for i in range(3):
for i in range(3):
print(i)

This will overwrite the outer i. It is legal but confusing. Letโ€™s use different names like i and j.

๐Ÿ›‘ Mistake 3: Too Many Nested Loops

Two levels are usually fine. Three levels can be okay. Four or more becomes hard to read and error-prone. If we need that many, letโ€™s consider breaking our code into functions.

๐Ÿงฉ Nested Loops Are Powerful

Nested loops let us work with grids, tables, combinations, and more. They are a fundamental tool in programming.

But they can also be slow if the numbers are large. For example, if both loops run 1000 times, the inner code runs 1,000,000 times. That is fine for a computer, but if we nest three loops of 1000, that is a billion times. So letโ€™s use them wisely.

Next, we will learn about Python Loop Patterns and use loops to create useful shapes and repeated structures.