← Back to Nested Loops
πŸ“–

Nested Loops β€” How They Work

1 of 6

Nested Loops β€” How They Work

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


Basic Example

for i in range(3): # Outer loop: runs 3 times for j in range(2): # Inner loop: runs 2 times PER outer iteration print(f"i={i}, j={j}")

Output:

i=0, j=0
i=0, j=1
i=1, j=0
i=1, j=1
i=2, j=0
i=2, j=1

Think of it like clock hands β€” the inner loop is the minute hand (spins fast) and the outer loop is the hour hand (moves after the minute hand completes a full cycle).


Counting Total Iterations

The total number of times the inner code runs = outer Γ— inner.

for i in range(4): # 4 times for j in range(3): # 3 times each print("*") # Runs 4 Γ— 3 = 12 times

Common Pattern: Grid / Rectangle

rows = 3 cols = 5 for r in range(rows): for c in range(cols): print("*", end=" ") print() # New line after each row

Output:

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

The end=" " makes print stay on the same line. The print() after the inner loop moves to the next line.


Common Pattern: Triangle

for i in range(1, 6): for j in range(i): print("*", end=" ") print()

Output:

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

The inner loop runs i times β€” so row 1 gets 1 star, row 2 gets 2 stars, etc.


Common Pattern: Multiplication Table

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

Output:

   1   2   3   4   5
   2   4   6   8  10
   3   6   9  12  15
   4   8  12  16  20
   5  10  15  20  25

Nested Loop with a List

teams = ["Red", "Blue"] players = ["Alex", "Sam", "Jordan"] for team in teams: for player in players: print(f"{player} joins {team} team")

Output:

Alex joins Red team
Sam joins Red team
Jordan joins Red team
Alex joins Blue team
Sam joins Blue team
Jordan joins Blue team

Using break in Nested Loops

break only exits the inner loop, not the outer one:

for i in range(3): for j in range(5): if j == 2: break # Only breaks the inner loop print(f"i={i}, j={j}") print(f"--- Done with i={i} ---")

Output:

i=0, j=0
i=0, j=1
--- Done with i=0 ---
i=1, j=0
i=1, j=1
--- Done with i=1 ---
i=2, j=0
i=2, j=1
--- Done with i=2 ---

Key Takeaways

  • Nested loops = a loop inside a loop
  • Inner loop runs completely for each outer iteration
  • Total iterations = outer count Γ— inner count
  • break only exits the innermost loop
  • Common uses: grids, tables, coordinate pairs, comparing all pairs
πŸ’»

Try it yourself

Code: Nested Loops β€” How They Work

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