Common Nested Loops Mistakes
The problem...
Your nested loop runs too many times. Or too few. Or it modifies the wrong variable. Or it breaks out of the wrong loop.
These are the mistakes almost every beginner makes with nested loops. At least once.
Mistake 1 — Wrong indentation
# Wrong — print is outside the inner loop
for i in range(1, 4):
for j in range(1, 4):
result = i * j
print(result) # prints only the last j value
# Right — print inside the inner loop
for i in range(1, 4):
for j in range(1, 4):
result = i * j
print(result)
Indentation defines which loop a line belongs to. One wrong indent — completely different behavior.
Mistake 2 — break stops the wrong loop
words = "red horn bull".split()
target = "o"
# Wrong — expecting to stop everything when found
for word in words:
for letter in word:
if letter == target:
print(f"Found in '{word}'")
break # stops the inner loop only — outer keeps going
# Found in 'horn'
# — outer loop still runs for 'bull'
break only stops the loop it's in. If you need to stop the outer loop too — use a flag variable.
found = False
for word in words:
for letter in word:
if letter == target:
print(f"Found in '{word}'")
found = True
break
if found:
break
Mistake 3 — Resetting the counter in the wrong place
word = "Bull"
vowels = "aeiou"
# Wrong — count resets on every inner iteration
for letter in word:
for vowel in vowels:
count = 0 # resets every time
if letter == vowel:
count += 1
# Right — define count before the outer loop
count = 0
for letter in word:
for vowel in vowels:
if letter == vowel:
count += 1
Define accumulators before the loop that uses them — never inside.
Mistake 4 — Losing track of iterations
for i in range(10):
for j in range(10):
for k in range(10):
print(i, j, k) # 1000 lines of output
Three nested loops of 10 = 1000 iterations. Nested loops multiply — keep sequences small and levels shallow. Two levels is usually the limit.
Mistake 5 — Using the same variable name in both loops
# Wrong — inner i overwrites outer i
for i in range(3):
for i in range(3): # same name — conflict
print(i)
# Right — different names
for i in range(3):
for j in range(3):
print(i, j)
Each loop needs its own variable. Reusing the same name in nested loops causes unexpected behavior.
What's really happening
Nested loops are powerful — and unforgiving. Indentation, variable names, break scope — every detail matters. One wrong indent or one shared variable name and the whole thing behaves differently than expected.
The mindset shift
Stop thinking: "It's just a loop inside a loop."
Start thinking: "Every level has its own scope, its own variables, its own break."
What you should understand now
- Indentation defines which loop a line belongs to — one space off changes everything
breakstops only its own loop — use a flag to stop the outer one- Define accumulators before the loop that uses them
- Nested loops multiply iterations — keep them small and shallow
- Use different variable names at each level