Loops Inside Loops Execution

๐Ÿท๏ธ Loops and Iteration / Nested Loops

๐Ÿง  Context Introduction

When you place one loop inside another loop, you create what's called a nested loop. This is a powerful concept that allows you to work with multi-dimensional data, perform repetitive tasks across multiple levels, and solve problems that require iterating over combinations of items. For engineers working with configurations, network topologies, or data grids, understanding how nested loops execute is essential for writing efficient and predictable code.


โš™๏ธ How Nested Loops Execute

The key to understanding nested loops is knowing the execution order:

  • The outer loop runs once for each of its iterations.
  • For each single iteration of the outer loop, the inner loop runs through all of its iterations completely.
  • This means if the outer loop runs 3 times and the inner loop runs 4 times, the inner loop's code executes a total of 12 times (3 ร— 4).

Simple mental model: Think of a clock. The minute hand (outer loop) moves once, while the second hand (inner loop) moves 60 times. Then the minute hand moves again, and the second hand starts over from the beginning.


๐Ÿ› ๏ธ Basic Structure of a Nested Loop

A nested loop follows this pattern:

  • Outer loop starts with its first iteration.
  • Inner loop runs completely from start to finish.
  • Control returns to the outer loop for its next iteration.
  • The inner loop resets and runs completely again.
  • This continues until the outer loop finishes.

Example in plain logic:

  • Outer loop: Count from 1 to 3
  • Inner loop: Count from 1 to 2
  • Execution produces: (1,1), (1,2), (2,1), (2,2), (3,1), (3,2)

๐Ÿ“Š Comparison: Single Loop vs Nested Loop

Feature Single Loop Nested Loop
Number of loops One loop running sequentially One loop inside another
Total iterations Equal to the loop's range Outer count ร— Inner count
Use case Processing a flat list Processing a table or grid
Complexity Simple, linear Multi-level, exponential growth
Reset behavior Loop variable increments normally Inner loop resets fully for each outer iteration

๐Ÿ•ต๏ธ Common Use Cases for Nested Loops

Engineers frequently encounter nested loops in these scenarios:

  • Processing configuration templates where you apply multiple settings across multiple servers
  • Checking connectivity between multiple source and destination endpoints
  • Generating combinations of parameters for testing or validation
  • Working with matrices or grids like IP address tables or subnet calculations
  • Comparing items from two different lists against each other

๐Ÿงช Execution Walkthrough Example

Imagine you have two lists: servers and services. You want to check which services are running on which servers.

  • Outer loop iterates through each server.
  • Inner loop iterates through each service.
  • For server A, the inner loop checks: service 1, service 2, service 3.
  • Then for server B, the inner loop checks again: service 1, service 2, service 3.
  • This continues for all servers.

The total number of checks performed equals: number of servers ร— number of services.


โš ๏ธ Important Considerations for Engineers

  • Performance impact: Nested loops multiply the work. If both loops are large, execution time can grow quickly. A 1000-item outer loop with a 1000-item inner loop creates 1 million iterations.
  • Variable naming: Always use clear, distinct variable names for the outer and inner loop counters. Using the same variable name in both loops will cause unexpected behavior.
  • Break and continue statements: A break inside the inner loop only exits the inner loop, not the outer loop. The outer loop continues with its next iteration.
  • Depth of nesting: You can nest loops more than two levels deep, but each additional level increases complexity and reduces readability. Three or more levels should be carefully considered.

๐ŸŽฏ Key Takeaway

Nested loops are a fundamental tool for handling multi-dimensional data and repetitive cross-referencing tasks. The critical insight is that the inner loop completes all its iterations for every single iteration of the outer loop. This multiplicative behavior is both the power and the potential performance pitfall of nested loops. Always consider whether a nested loop is truly necessary, or if a more efficient approach like dictionary lookups or set operations could achieve the same result with less computational overhead.


A nested loop is a loop placed inside another loop, where the inner loop completes all its iterations for each single iteration of the outer loop.


๐Ÿ”ง Example 1: Basic Nested Loop with Two Numbers

This example shows a simple outer loop running from 1 to 2, with an inner loop running from 1 to 3 for each outer value.

outer = 1
while outer <= 2:
    inner = 1
    while inner <= 3:
        print("Outer:", outer, "Inner:", inner)
        inner = inner + 1
    outer = outer + 1

๐Ÿ“ค Output: Outer: 1 Inner: 1
Outer: 1 Inner: 2
Outer: 1 Inner: 3
Outer: 2 Inner: 1
Outer: 2 Inner: 2
Outer: 2 Inner: 3


๐Ÿ”ง Example 2: Nested Loop with Multiplication Table Row

This example prints a single row of the multiplication table for the number 3.

number = 3
multiplier = 1
while multiplier <= 5:
    result = number * multiplier
    print(number, "x", multiplier, "=", result)
    multiplier = multiplier + 1

๐Ÿ“ค Output: 3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15


๐Ÿ”ง Example 3: Full Multiplication Table with Nested Loops

This example uses nested loops to print a complete multiplication table from 1 to 3.

row = 1
while row <= 3:
    column = 1
    while column <= 3:
        product = row * column
        print(row, "x", column, "=", product)
        column = column + 1
    print("---")
    row = row + 1

๐Ÿ“ค Output: **1 x 1 = 1
1 x 2 = 2
1 x 3 = 3


2 x 1 = 2
2 x 2 = 4
2 x 3 = 6


3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---**


๐Ÿ”ง Example 4: Building a Simple Grid Pattern

This example uses nested loops to print a 3x3 grid of asterisks.

row = 1
while row <= 3:
    column = 1
    line = ""
    while column <= 3:
        line = line + "* "
        column = column + 1
    print(line)
    row = row + 1

๐Ÿ“ค Output: *** * *
* * *
* * * **


๐Ÿ”ง Example 5: Finding Pairs That Sum to a Target

This example uses nested loops to find all pairs of numbers from two lists that add up to 10.

list_a = [1, 2, 3]
list_b = [7, 8, 9]
target = 10
index_a = 0

while index_a < len(list_a):
    index_b = 0
    while index_b < len(list_b):
        if list_a[index_a] + list_b[index_b] == target:
            print(list_a[index_a], "+", list_b[index_b], "=", target)
        index_b = index_b + 1
    index_a = index_a + 1

๐Ÿ“ค Output: 1 + 9 = 10
2 + 8 = 10
3 + 7 = 10


๐Ÿ“Š Comparison Table

Concept Outer Loop Inner Loop Total Iterations
Basic nested loop 2 iterations 3 iterations 6
Single row table 1 iteration 5 iterations 5
Full multiplication table 3 iterations 3 iterations 9
Grid pattern 3 iterations 3 iterations 9
Pair finding 3 iterations 3 iterations 9

๐Ÿง  Context Introduction

When you place one loop inside another loop, you create what's called a nested loop. This is a powerful concept that allows you to work with multi-dimensional data, perform repetitive tasks across multiple levels, and solve problems that require iterating over combinations of items. For engineers working with configurations, network topologies, or data grids, understanding how nested loops execute is essential for writing efficient and predictable code.


โš™๏ธ How Nested Loops Execute

The key to understanding nested loops is knowing the execution order:

  • The outer loop runs once for each of its iterations.
  • For each single iteration of the outer loop, the inner loop runs through all of its iterations completely.
  • This means if the outer loop runs 3 times and the inner loop runs 4 times, the inner loop's code executes a total of 12 times (3 ร— 4).

Simple mental model: Think of a clock. The minute hand (outer loop) moves once, while the second hand (inner loop) moves 60 times. Then the minute hand moves again, and the second hand starts over from the beginning.


๐Ÿ› ๏ธ Basic Structure of a Nested Loop

A nested loop follows this pattern:

  • Outer loop starts with its first iteration.
  • Inner loop runs completely from start to finish.
  • Control returns to the outer loop for its next iteration.
  • The inner loop resets and runs completely again.
  • This continues until the outer loop finishes.

Example in plain logic:

  • Outer loop: Count from 1 to 3
  • Inner loop: Count from 1 to 2
  • Execution produces: (1,1), (1,2), (2,1), (2,2), (3,1), (3,2)

๐Ÿ“Š Comparison: Single Loop vs Nested Loop

Feature Single Loop Nested Loop
Number of loops One loop running sequentially One loop inside another
Total iterations Equal to the loop's range Outer count ร— Inner count
Use case Processing a flat list Processing a table or grid
Complexity Simple, linear Multi-level, exponential growth
Reset behavior Loop variable increments normally Inner loop resets fully for each outer iteration

๐Ÿ•ต๏ธ Common Use Cases for Nested Loops

Engineers frequently encounter nested loops in these scenarios:

  • Processing configuration templates where you apply multiple settings across multiple servers
  • Checking connectivity between multiple source and destination endpoints
  • Generating combinations of parameters for testing or validation
  • Working with matrices or grids like IP address tables or subnet calculations
  • Comparing items from two different lists against each other

๐Ÿงช Execution Walkthrough Example

Imagine you have two lists: servers and services. You want to check which services are running on which servers.

  • Outer loop iterates through each server.
  • Inner loop iterates through each service.
  • For server A, the inner loop checks: service 1, service 2, service 3.
  • Then for server B, the inner loop checks again: service 1, service 2, service 3.
  • This continues for all servers.

The total number of checks performed equals: number of servers ร— number of services.


โš ๏ธ Important Considerations for Engineers

  • Performance impact: Nested loops multiply the work. If both loops are large, execution time can grow quickly. A 1000-item outer loop with a 1000-item inner loop creates 1 million iterations.
  • Variable naming: Always use clear, distinct variable names for the outer and inner loop counters. Using the same variable name in both loops will cause unexpected behavior.
  • Break and continue statements: A break inside the inner loop only exits the inner loop, not the outer loop. The outer loop continues with its next iteration.
  • Depth of nesting: You can nest loops more than two levels deep, but each additional level increases complexity and reduces readability. Three or more levels should be carefully considered.

๐ŸŽฏ Key Takeaway

Nested loops are a fundamental tool for handling multi-dimensional data and repetitive cross-referencing tasks. The critical insight is that the inner loop completes all its iterations for every single iteration of the outer loop. This multiplicative behavior is both the power and the potential performance pitfall of nested loops. Always consider whether a nested loop is truly necessary, or if a more efficient approach like dictionary lookups or set operations could achieve the same result with less computational overhead.

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

A nested loop is a loop placed inside another loop, where the inner loop completes all its iterations for each single iteration of the outer loop.


๐Ÿ”ง Example 1: Basic Nested Loop with Two Numbers

This example shows a simple outer loop running from 1 to 2, with an inner loop running from 1 to 3 for each outer value.

outer = 1
while outer <= 2:
    inner = 1
    while inner <= 3:
        print("Outer:", outer, "Inner:", inner)
        inner = inner + 1
    outer = outer + 1

๐Ÿ“ค Output: Outer: 1 Inner: 1
Outer: 1 Inner: 2
Outer: 1 Inner: 3
Outer: 2 Inner: 1
Outer: 2 Inner: 2
Outer: 2 Inner: 3


๐Ÿ”ง Example 2: Nested Loop with Multiplication Table Row

This example prints a single row of the multiplication table for the number 3.

number = 3
multiplier = 1
while multiplier <= 5:
    result = number * multiplier
    print(number, "x", multiplier, "=", result)
    multiplier = multiplier + 1

๐Ÿ“ค Output: 3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
3 x 4 = 12
3 x 5 = 15


๐Ÿ”ง Example 3: Full Multiplication Table with Nested Loops

This example uses nested loops to print a complete multiplication table from 1 to 3.

row = 1
while row <= 3:
    column = 1
    while column <= 3:
        product = row * column
        print(row, "x", column, "=", product)
        column = column + 1
    print("---")
    row = row + 1

๐Ÿ“ค Output: **1 x 1 = 1
1 x 2 = 2
1 x 3 = 3


2 x 1 = 2
2 x 2 = 4
2 x 3 = 6


3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---**


๐Ÿ”ง Example 4: Building a Simple Grid Pattern

This example uses nested loops to print a 3x3 grid of asterisks.

row = 1
while row <= 3:
    column = 1
    line = ""
    while column <= 3:
        line = line + "* "
        column = column + 1
    print(line)
    row = row + 1

๐Ÿ“ค Output: *** * *
* * *
* * * **


๐Ÿ”ง Example 5: Finding Pairs That Sum to a Target

This example uses nested loops to find all pairs of numbers from two lists that add up to 10.

list_a = [1, 2, 3]
list_b = [7, 8, 9]
target = 10
index_a = 0

while index_a < len(list_a):
    index_b = 0
    while index_b < len(list_b):
        if list_a[index_a] + list_b[index_b] == target:
            print(list_a[index_a], "+", list_b[index_b], "=", target)
        index_b = index_b + 1
    index_a = index_a + 1

๐Ÿ“ค Output: 1 + 9 = 10
2 + 8 = 10
3 + 7 = 10


๐Ÿ“Š Comparison Table

Concept Outer Loop Inner Loop Total Iterations
Basic nested loop 2 iterations 3 iterations 6
Single row table 1 iteration 5 iterations 5
Full multiplication table 3 iterations 3 iterations 9
Grid pattern 3 iterations 3 iterations 9
Pair finding 3 iterations 3 iterations 9