← Back to Nested Loops
πŸ’‘

Tips & Common Mistakes

6 of 6

Nested Loops β€” Tips & Common Mistakes

Common Mistake 1: Forgetting print()

If you forget the print() after the inner loop, everything stays on one line:

# ❌ Wrong β€” no newline for r in range(3): for c in range(4): print("*", end=" ") # Output: * * * * * * * * * * * * (all on one line!) # βœ… Correct β€” add print() after inner loop for r in range(3): for c in range(4): print("*", end=" ") print() # ← this moves to the next line

Common Mistake 2: Wrong Variable Names

Using the same variable for both loops causes bugs:

# ❌ Wrong β€” both loops use 'i' for i in range(3): for i in range(4): # This overwrites the outer 'i'! print(i, end=" ") print() # βœ… Correct β€” use different names for i in range(3): for j in range(4): print(j, end=" ") print()

Common Mistake 3: Off-by-One in Range

Remember: range(n) goes from 0 to n-1, and range(a, b) goes from a to b-1.

# Want to print 1 to 5? range(5) # gives 0, 1, 2, 3, 4 ← starts at 0! range(1, 5) # gives 1, 2, 3, 4 ← misses 5! range(1, 6) # gives 1, 2, 3, 4, 5 ← correct!

Common Mistake 4: break Only Breaks the Inner Loop

for i in range(5): for j in range(5): if j == 2: break # Only exits the inner loop! # Outer loop keeps going...

If you need to break both loops, use a flag:

done = False for i in range(5): for j in range(5): if some_condition: done = True break if done: break

Debugging Tip: Add Print Statements

When your nested loop isn't working, add prints to see what's happening:

for i in range(3): print(f"--- Outer loop: i = {i} ---") for j in range(3): print(f" Inner loop: j = {j}")

This shows you exactly how the loops are running.


Quick Reference

PatternOuterInnerTotal
3Γ—4 gridrange(3)range(4)12 runs
Trianglerange(1, n+1)range(i)varies
All pairsrange(len(list))range(i+1, len(list))nΓ—(n-1)/2
Times tablerange(1, 13)(just multiply)12 runs

When to Use Nested Loops

  • Grids and tables β€” rows Γ— columns
  • Comparing all pairs β€” matching, finding duplicates
  • Pattern printing β€” stars, numbers, shapes
  • 2D data β€” game boards, spreadsheets, images
πŸ’»

Try it yourself

Code: Tips & Common Mistakes

Loading Python runtime…
Python …
Loading...
Output
Click "Run" to execute your code...
ℹ️ About this Python environment

βœ… Standard library: heapq, collections, itertools, math, random, functools, datetime, bisect

βœ… Functions, classes, recursion, print()

❌ No file system, subprocess, OS access, or network requests

❌ No pip install (all supported modules are pre-loaded)

⏱️ 5 second execution time limit