Bird
Raised Fist0
Pythonprogramming~15 mins

Nested for loop execution in Python - Deep Dive

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Overview - Nested for loop execution
What is it?
A nested for loop is a loop inside another loop. It means one loop runs completely for each step of the outer loop. This helps when you want to repeat actions in a grid or pairs, like rows and columns. It is common in tasks like printing patterns or working with tables.
Why it matters
Nested loops let us handle complex repeated tasks easily, like checking every seat in a theater or every cell in a spreadsheet. Without nested loops, we would write many repetitive lines of code, making programs long and hard to change. They save time and make code clearer.
Where it fits
Before learning nested loops, you should understand simple for loops and how they repeat actions. After mastering nested loops, you can learn about more advanced loops like while loops, list comprehensions, and working with multi-dimensional data structures.
Mental Model
Core Idea
A nested for loop runs the entire inner loop for each single step of the outer loop, like checking every item in a grid one row at a time.
Think of it like...
Imagine you are reading a book with chapters and pages. For each chapter (outer loop), you read every page (inner loop) before moving to the next chapter.
Outer Loop (Chapters)
┌───────────────┐
│ Chapter 1     │
│ ┌───────────┐ │
│ │ Page 1    │ │
│ │ Page 2    │ │
│ │ Page 3    │ │
│ └───────────┘ │
│ Chapter 2     │
│ ┌───────────┐ │
│ │ Page 1    │ │
│ │ Page 2    │ │
│ │ Page 3    │ │
│ └───────────┘ │
└───────────────┘
Build-Up - 7 Steps
1
FoundationUnderstanding simple for loops
🤔
Concept: Learn how a single for loop repeats actions over a list or range.
In Python, a for loop repeats code for each item in a sequence. For example: for number in range(3): print(number) This prints numbers 0, 1, and 2 one by one.
Result
0 1 2
Understanding how a single loop repeats actions is the base for grasping nested loops.
2
FoundationIntroducing loop nesting concept
🤔
Concept: Learn that loops can be placed inside other loops to repeat multiple layers of actions.
You can put one for loop inside another. The inner loop runs fully each time the outer loop runs once. For example: for i in range(2): for j in range(3): print(i, j) This prints pairs of i and j values.
Result
0 0 0 1 0 2 1 0 1 1 1 2
Knowing that loops can be nested helps you handle tasks with multiple repeating steps.
3
IntermediateOrder of execution in nested loops
🤔Before reading on: Do you think the inner loop runs once or multiple times per outer loop step? Commit to your answer.
Concept: Understand that the inner loop completes all its steps for each single step of the outer loop.
In nested loops, the outer loop picks one value, then the inner loop runs completely for that value. Then the outer loop moves to the next value, and the inner loop runs again fully. This repeats until the outer loop finishes. Example: for i in range(2): print('Outer loop:', i) for j in range(3): print(' Inner loop:', j)
Result
Outer loop: 0 Inner loop: 0 Inner loop: 1 Inner loop: 2 Outer loop: 1 Inner loop: 0 Inner loop: 1 Inner loop: 2
Understanding the full inner loop runs per outer step clarifies how nested loops multiply repetitions.
4
IntermediateUsing nested loops for grids and tables
🤔
Concept: Learn how nested loops help process two-dimensional data like rows and columns.
Imagine a table with rows and columns. The outer loop can go through rows, and the inner loop through columns. For example, printing a 3x3 grid: for row in range(3): for col in range(3): print(f'({row},{col})', end=' ') print()
Result
(0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2)
Nested loops naturally fit tasks involving two dimensions, making code simpler and clearer.
5
IntermediateControlling nested loop flow with break and continue
🤔Before reading on: What happens if you use break inside the inner loop? Does it stop both loops or just one? Commit to your answer.
Concept: Learn how break and continue affect only the loop they are inside, not all nested loops.
Using break inside the inner loop stops only that inner loop, then the outer loop continues. Using continue skips the current inner loop step. Example: for i in range(2): for j in range(3): if j == 1: break print(i, j)
Result
0 0 1 0
Knowing break and continue affect only their own loop prevents confusion and bugs in nested loops.
6
AdvancedPerformance considerations of nested loops
🤔Before reading on: Do you think nested loops always run quickly? What happens when loops get very large? Commit to your answer.
Concept: Understand that nested loops multiply the number of steps, which can slow down programs if loops are large.
If the outer loop runs N times and the inner loop runs M times, total steps are N×M. For big N and M, this grows fast and can make programs slow. Example: for i in range(1000): for j in range(1000): pass # 1,000,000 steps This can be slow on big data.
Result
Program runs slower as loops grow larger.
Understanding nested loops' cost helps you write efficient code and avoid slowdowns.
7
ExpertAdvanced nesting: multiple levels and comprehension
🤔Before reading on: Can you predict how three nested loops behave compared to two? How does list comprehension replace nested loops? Commit to your answer.
Concept: Learn that loops can nest many levels deep, and Python offers list comprehensions to write nested loops more compactly.
You can nest loops inside loops multiple times: for i in range(2): for j in range(2): for k in range(2): print(i, j, k) This prints all combinations of i, j, k. List comprehension example: pairs = [(i, j) for i in range(2) for j in range(3)] print(pairs)
Result
0 0 0 0 0 1 0 1 0 0 1 1 1 0 0 1 0 1 1 1 0 1 1 1 [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]
Knowing multiple nesting levels and comprehension syntax unlocks powerful, concise code patterns.
Under the Hood
When Python runs nested loops, it keeps track of each loop's current position separately. The outer loop sets a value, then the inner loop runs fully, updating its own counter each time. After the inner loop finishes, control returns to the outer loop to pick the next value. This happens using the call stack and loop counters internally.
Why designed this way?
Nested loops follow a simple, consistent rule: inner loops complete fully for each outer step. This design matches how we think about repeated tasks in layers, like rows and columns. Alternatives like flattening loops lose clarity and flexibility, so nesting keeps code readable and logical.
┌─────────────┐
│ Outer Loop  │
│ index i     │
│ ┌─────────┐ │
│ │ Inner   │ │
│ │ Loop    │ │
│ │ index j │ │
│ └─────────┘ │
└─────────────┘

Execution flow:
1. Outer loop picks i
2. Inner loop runs all j
3. Outer loop picks next i
4. Repeat until done
Myth Busters - 4 Common Misconceptions
Quick: Does break inside inner loop stop the outer loop too? Commit yes or no.
Common Belief:Break inside the inner loop stops all loops immediately.
Tap to reveal reality
Reality:Break only stops the loop it is inside; outer loops continue normally.
Why it matters:Misunderstanding this causes unexpected behavior and bugs when trying to exit multiple loops.
Quick: Does nested loop always run faster than separate loops? Commit yes or no.
Common Belief:Nested loops are always efficient and fast.
Tap to reveal reality
Reality:Nested loops multiply steps, which can slow down programs significantly for large data.
Why it matters:Ignoring performance costs leads to slow, unresponsive programs.
Quick: Can you use the same variable name in inner and outer loops safely? Commit yes or no.
Common Belief:Using the same variable name in nested loops is fine and causes no issues.
Tap to reveal reality
Reality:Using the same variable name causes the inner loop to overwrite the outer loop variable, leading to bugs.
Why it matters:Variable shadowing causes confusing errors and wrong results.
Quick: Does the inner loop run before the outer loop starts? Commit yes or no.
Common Belief:The inner loop runs once before the outer loop starts.
Tap to reveal reality
Reality:The inner loop runs repeatedly inside each step of the outer loop, not before it.
Why it matters:Misunderstanding execution order leads to wrong assumptions about program flow.
Expert Zone
1
Nested loops can be replaced by itertools.product for cleaner, memory-efficient iteration over combinations.
2
Deeply nested loops often signal a need to rethink algorithm design, possibly using recursion or vectorized operations.
3
Python's list comprehensions and generator expressions can express nested loops more concisely and sometimes more efficiently.
When NOT to use
Avoid nested loops when data size is very large and performance is critical; consider vectorized libraries like NumPy or algorithms with lower complexity instead.
Production Patterns
Nested loops are used in matrix operations, image processing, and generating combinations. Professionals often combine them with conditionals and break statements to optimize performance.
Connections
Cartesian product
Nested loops implement the Cartesian product by pairing every element of one set with every element of another.
Understanding nested loops helps grasp how Cartesian products generate all possible pairs in math and programming.
Matrix multiplication
Nested loops are the basic method to multiply matrices by iterating rows and columns.
Knowing nested loops clarifies how matrix math works step-by-step in computer programs.
Nested iteration in linguistics
Nested loops mirror how sentences have nested structures, like clauses inside clauses.
Recognizing nested patterns in language helps understand recursion and layered processes in programming.
Common Pitfalls
#1Using the same variable name for both loops causes unexpected behavior.
Wrong approach:for i in range(3): for i in range(2): print(i)
Correct approach:for i in range(3): for j in range(2): print(j)
Root cause:Variable shadowing overwrites the outer loop variable, confusing the program.
#2Expecting break in inner loop to stop outer loop too.
Wrong approach:for i in range(3): for j in range(3): if j == 1: break print(i, j) print('Outer loop continues')
Correct approach:Use a flag or exception to break outer loop if needed, or restructure code.
Root cause:Break only exits the current loop, not all nested loops.
#3Writing nested loops with large ranges without considering performance.
Wrong approach:for i in range(10000): for j in range(10000): print(i, j)
Correct approach:# Use optimized libraries or algorithms instead import numpy as np # Use vectorized operations
Root cause:Nested loops multiply steps, causing slow execution on big data.
Key Takeaways
Nested for loops run the entire inner loop for each step of the outer loop, enabling repeated actions in layers.
They are essential for working with grids, tables, and combinations in programming.
Break and continue affect only the loop they are inside, not all nested loops.
Nested loops multiply the number of steps, so large loops can slow down programs significantly.
Advanced Python features like list comprehensions and itertools can replace nested loops for cleaner and faster code.

Practice

(1/5)
1. What does a nested for loop do in Python?
for i in range(2):
for j in range(3):
print(i, j)
easy
A. Runs the inner loop fully for each outer loop step
B. Runs both loops only once
C. Runs the outer loop fully for each inner loop step
D. Runs only the outer loop

Solution

  1. Step 1: Understand nested loop structure

    The outer loop runs 2 times (i=0,1). For each i, the inner loop runs 3 times (j=0,1,2).
  2. Step 2: Observe loop execution order

    For each i, the inner loop completes all its iterations before the outer loop moves to next i.
  3. Final Answer:

    Runs the inner loop fully for each outer loop step -> Option A
  4. Quick Check:

    Inner loop runs fully per outer loop [OK]
Hint: Inner loop runs completely inside each outer loop step [OK]
Common Mistakes:
  • Thinking outer loop runs inside inner loop
  • Assuming loops run only once
  • Confusing loop order
2. Which of the following is the correct syntax for a nested for loop in Python?
easy
A. for i in range(3): for j in range(2): print(i, j)
B. for i in range(3): for j in range(2): print(i, j)
C. for i in range(3): for j in range(2): print(i, j)
D. for i in range(3): for j in range(2): print(i, j)

Solution

  1. Step 1: Check indentation rules

    Python requires consistent indentation to define nested blocks. Inner loop must be indented inside outer loop.
  2. Step 2: Identify correct indentation

    for i in range(3): for j in range(2): print(i, j) uses 4 spaces indentation for inner loop and print statement, which is correct.
  3. Final Answer:

    for i in range(3):\n for j in range(2):\n print(i, j) -> Option B
  4. Quick Check:

    Proper indentation = for i in range(3): for j in range(2): print(i, j) [OK]
Hint: Indent inner loop inside outer loop with spaces [OK]
Common Mistakes:
  • Missing indentation for inner loop
  • Incorrect indentation for print
  • Writing loops on same line without colon
3. What is the output of this code?
for i in range(2):
    for j in range(2):
        print(i + j, end=' ')
    print()
medium
A. 0 1 \n0 1
B. 1 2 \n2 3
C. 0 1 1 2
D. 0 1 \n1 2

Solution

  1. Step 1: Calculate inner loop sums for i=0

    j=0: 0+0=0, j=1: 0+1=1 -> prints '0 1 '
  2. Step 2: Calculate inner loop sums for i=1

    j=0: 1+0=1, j=1: 1+1=2 -> prints '1 2 '
  3. Final Answer:

    0 1 \n1 2 -> Option D
  4. Quick Check:

    Sum of i and j per line = 0 1 \n1 2 [OK]
Hint: Add i and j for each inner loop iteration [OK]
Common Mistakes:
  • Ignoring print() creates new line
  • Adding values incorrectly
  • Confusing end=' ' usage
4. Find the error in this nested loop code:
for i in range(3):
for j in range(2):
    print(i, j)
medium
A. print statement should be outside loops
B. Missing colon after inner for loop
C. Inner loop not indented inside outer loop
D. range(2) should be range(3)

Solution

  1. Step 1: Check indentation of inner loop

    Inner for loop must be indented inside outer loop to be nested properly.
  2. Step 2: Identify correct indentation

    Here, inner loop is at same level as outer loop, causing IndentationError.
  3. Final Answer:

    Inner loop not indented inside outer loop -> Option C
  4. Quick Check:

    Indent inner loop inside outer loop [OK]
Hint: Indent inner loop under outer loop to fix error [OK]
Common Mistakes:
  • Not indenting inner loop
  • Misplacing colons
  • Wrong range values
5. How many times will the print statement execute in this nested loop?
for i in range(4):
    for j in range(3):
        for k in range(2):
            print(i, j, k)
hard
A. 24
B. 12
C. 36
D. 9

Solution

  1. Step 1: Calculate iterations of each loop

    Outer loop: 4 times (i=0..3), middle loop: 3 times (j=0..2), inner loop: 2 times (k=0..1).
  2. Step 2: Multiply iterations for total prints

    Total = 4 * 3 * 2 = 24 print executions.
  3. Step 3: Re-check options

    36 says 36, but calculation is 24, so correct is 24.
  4. Final Answer:

    24 -> Option A
  5. Quick Check:

    4*3*2 = 24 prints [OK]
Hint: Multiply all loop ranges for total executions [OK]
Common Mistakes:
  • Adding instead of multiplying loop counts
  • Counting only outer loops
  • Misreading loop ranges