Python Nested Loops
Table of Contents
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=1i=1, j=2i=1, j=3i=2, j=1i=2, j=2i=2, j=3i=3, j=1i=3, j=2i=3, j=3Let 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 = 11 x 2 = 21 x 3 = 31 x 4 = 41 x 5 = 5---------------2 x 1 = 22 x 2 = 42 x 3 = 62 x 4 = 82 x 5 = 10---------------... and so onFor 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).
iis the current row number. - For each row, the inner loop runs
itimes. - 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 = 1while i <= 3: j = 1 while j <= 3: print(f"i={i}, j={j}") j += 1 i += 1This 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 += 1This 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=1i=2, j=1i=3, j=1For 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=1i=1, j=3i=2, j=1i=2, j=3i=3, j=1i=3, j=3When 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 R1S4R2S1 R2S2 R2S3 R2S4R3S1 R3S2 R3S3 R3S4That 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 = 1while i <= 3: j = 1 # This must be inside the outer loop while j <= 3: print(i, j) j += 1 i += 1If 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.