🐍
Syllabus / Python Programming / Phase 2: Loops, Conditional Statements, Functions (Days 6–10)
Beginner

Nested Loops and Pattern Programs

📂 Phase 2: Loops, Conditional Statements, Functions (Days 6–10) · Python Programming

A nested loop is simply a loop placed inside another loop. For every single iteration of the outer loop, the inner loop runs through its own entire range of iterations before control returns to the outer loop — this is the foundation for working with grids, matrices, and pattern-printing problems.

Basic Nested Loop Structure

for i in range(1, 3):
    print(f"Outer: {i}")
    for j in range(1, 4):
        print(f"  Inner: {j}")
# Outer loop runs 2 times; inner loop runs 3 times for EACH outer pass
# Total inner executions: 2 * 3 = 6

Classic Use Case: Multiplication Table

for i in range(1, 4):
    for j in range(1, 4):
        print(i * j, end=" ")
    print()   # newline after each row
# 1 2 3
# 2 4 6
# 3 6 9

The end=" " keyword argument tells print() to use a space instead of its default newline, so numbers stay on the same row until the inner loop finishes.

Pattern Printing — A Common Interview Warm-Up

# Right-angled triangle of stars
for i in range(1, 6):
    print("* " * i)
# *
# * *
# * * *
# * * * *
# * * * * *
# Same triangle, written explicitly with a nested loop
for i in range(1, 6):
    for j in range(i):
        print("*", end=" ")
    print()

An Inverted Triangle

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

A Number Pyramid

for i in range(1, 6):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5

Time Complexity of Nested Loops

If the outer loop runs n times and the inner loop runs m times for each outer pass, the total number of inner-loop executions is n × m. When both loops run over the same input size n, this gives O(n²) time complexity — a concept that resurfaces constantly when analyzing brute-force algorithms in data structures problems.

Nested Loops Over 2D Data

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

for row in matrix:
    for value in row:
        print(value, end=" ")
    print()
# 1 2 3
# 4 5 6
# 7 8 9
Interview tip: Pattern-printing questions (triangles, pyramids, diamonds) show up constantly in early technical screening rounds, specifically to test comfort with nested loop logic and string repetition — practice a few different shapes, not just triangles, since interviewers often ask you to adapt a known pattern on the spot.