Python Basics — Nested Loops

3 minute read

Nested Loops

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

Basic Nesting

for i in range(1, 4):        # Outer loop
    for j in range(1, 4):    # Inner loop
        print(f"({i},{j})", end=" ")
    print()  # New line after inner loop completes

Output:

(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

The inner loop runs 3 times for each iteration of the outer loop, giving 9 total iterations.

Pattern Printing

Right Triangle

rows = 5

for i in range(1, rows + 1):
    print("* " * i)

Output:

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

Number Triangle

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

Output:

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Inverted Triangle

for i in range(5, 0, -1):
    print("* " * i)

Output:

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

Matrix / Grid Operations

Creating a Matrix

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]

for row in matrix:
    for item in row:
        print(f"{item:3}", end="")
    print()

Output:

  1  2  3
  4  5  6
  7  8  9

Matrix Transposition

matrix = [
    [1, 2, 3],
    [4, 5, 6],
]

# Transpose: swap rows and columns
rows = len(matrix)
cols = len(matrix[0])
transposed = []

for j in range(cols):
    new_row = []
    for i in range(rows):
        new_row.append(matrix[i][j])
    transposed.append(new_row)

for row in transposed:
    print(row)

Output:

[1, 4]
[2, 5]
[3, 6]

Performance Considerations

Nested loops multiply iterations. Be mindful of time complexity:

Outer × Inner Iterations Example
10 × 10 100 Instant
100 × 100 10,000 Instant
1,000 × 1,000 1,000,000 Noticeable
10,000 × 10,000 100,000,000 Slow
# O(n²) — avoid for very large data
for i in range(n):
    for j in range(n):
        # runs n² times
        pass

Breaking Out of Nested Loops

break only exits the innermost loop:

for i in range(3):
    for j in range(3):
        if j == 1:
            break  # Only breaks inner loop
        print(f"({i},{j})", end=" ")
    print()

Output:

(0,0)
(1,0)
(2,0)

Breaking Both Loops with a Flag

found = False

for i in range(5):
    for j in range(5):
        if i * j == 12:
            print(f"Found: {i} * {j} = 12")
            found = True
            break
    if found:
        break

Output:

Found: 3 * 4 = 12

Breaking Both Loops with a Function

A cleaner approach — return exits the entire function:

def find_product(target):
    for i in range(1, 10):
        for j in range(1, 10):
            if i * j == target:
                return (i, j)
    return None

result = find_product(12)
print(f"{result[0]} × {result[1]} = 12")  # 2 × 6 = 12

itertools.product() Alternative

For simple nested iteration, itertools.product() can replace nested for loops:

from itertools import product

# Nested loops
for i in range(3):
    for j in range(3):
        print(f"({i},{j})", end=" ")
    print()

# Equivalent with product
for i, j in product(range(3), range(3)):
    print(f"({i},{j})", end=" ")

Generating Combinations

from itertools import product

sizes = ["S", "M", "L"]
colors = ["Red", "Blue"]

for size, color in product(sizes, colors):
    print(f"{size}-{color}")

Output:

S-Red
S-Blue
M-Red
M-Blue
L-Red
L-Blue

Multiplication Table

size = 5

# Header
print("   ", end="")
for j in range(1, size + 1):
    print(f"{j:4}", end="")
print()
print("   " + "----" * size)

# Body
for i in range(1, size + 1):
    print(f"{i:2} |", end="")
    for j in range(1, size + 1):
        print(f"{i*j:4}", end="")
    print()

Output:

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

Summary

  • Nested loops run the inner loop completely for each outer iteration
  • Total iterations = outer count × inner count
  • Use for pattern printing, matrix operations, and generating combinations
  • break only exits the innermost loop — use flags or functions to exit both
  • itertools.product() is a cleaner alternative for simple nested iteration
  • Watch performance: O(n²) grows fast with large inputs

Next up: Practice Exercises →

Updated: