Academic Block

Nested LoopsGet Certified

What Are Nested Loops?

A nested loop is a loop placed inside the body of another loop. The outer loop controls how many times the inner loop runs completely. Nested loops are useful for working with tables, grids, patterns, combinations, and any data that has two or more dimensions. They allow a program to repeat one task for every step of another task, making it easier to process related groups of values. Understanding how the two levels interact is important before building more complex examples.

  • The outer loop runs once for each “row” (or major step).
  • The inner loop runs completely for every single iteration of the outer loop.
  • You can nest for inside for, while inside while, or mix the two.
  • In this browser environment keep both the outer and inner limits very small (usually 3–5) so the page stays responsive.

Basic Nested for Loops

The most common pattern is a for loop inside another for loop. The outer loop selects a value or position, while the inner loop performs a repeated operation for that selection. Python finishes all iterations of the inner loop before moving to the next outer iteration. This predictable order makes nested for loops especially useful when processing rows and columns or comparing items from different groups.

Try It: Simple Row-and-Column Grid

This example prints a small grid of coordinates. The outer loop controls the row; the inner loop controls the column.

What this code does: It creates a 3×3 grid. For every row number it prints all column numbers on the same line, then moves to the next row.
for row in range(1, 4):
    for col in range(1, 4):
        print(f"({row},{col})", end="  ")
    print()          # new line after each row

Try It: Small Multiplication Table

A classic use of nested loops is printing a multiplication table. We keep it to 1–4 so the output stays short.

What this code does: The outer loop supplies the left factor (1–4). The inner loop multiplies it by 1–4 and prints each product. A header row is printed first for clarity.
print("   ", end="")
for j in range(1, 5):
    print(f"{j:4}", end="")
print()
print("-" * 20)

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

Pattern Printing with Nested Loops

Nested loops are perfect for drawing simple text patterns. Each outer iteration can represent a new line, while the inner loop decides what appears on that line. By changing the inner loop’s range or the value it prints, you can create triangles, rectangles, number sequences, and other designs. These exercises also help you understand how loop counters control the amount of output produced on each row.

Try It: Right-Angled Triangle of Stars

Each row contains one more star than the previous row.

What this code does: The outer loop runs 5 times (one pass per row). The inner loop prints as many stars as the current row number.
for i in range(1, 6):
    for j in range(i):
        print("*", end=" ")
    print()

Try It: Number Pyramid

A slightly richer pattern that prints increasing numbers on each row.

What this code does: Each row starts with 1 and counts up to the row number. The result looks like a small number triangle.
for i in range(1, 6):
    for j in range(1, i + 1):
        print(j, end=" ")
    print()

Nested while Loops

The same ideas work with while loops. Remember to update the counters yourself and keep the limits small. Unlike a for loop that takes values from an iterable, a while loop continues as long as its condition remains true. When nesting these loops, reset the inner counter at the beginning of each outer iteration so that the inner loop can run again.

Try It: Nested while Countdown Grid

Both the outer and inner loops are written with while. The example stays tiny (3×3).

What this code does: The outer counter runs from 3 down to 1. For each outer value the inner counter also runs from 3 down to 1, printing a small grid of pairs.
i = 3
while i >= 1:
    j = 3
    while j >= 1:
        print(f"({i},{j})", end="  ")
        j = j - 1
    print()
    i = i - 1

Mixing for and while

You are free to put a for loop inside a while loop or the other way around. The choice depends on how each part of the task should repeat: use for when processing a known sequence or range, and use while when repetition depends on a condition. Combining them lets each loop handle the kind of repetition that suits it best.

Try It: while Outside, for Inside

A while loop controls the number of groups; a for loop prints the members of each group.

What this code does: The outer while loop runs three times (group 1, 2, 3). Inside each group a for loop prints the numbers 1–4.
group = 1
while group <= 3:
    print(f"Group {group}:", end=" ")
    for n in range(1, 5):
        print(n, end=" ")
    print()
    group = group + 1

Nested Loops with break and continue

Remember that break and continue affect only the innermost loop that contains them. This is important when a program has several levels of repetition because an instruction inside the inner loop does not automatically change the outer loop. You can use these statements to stop or skip specific inner iterations while allowing the outer loop to carry on with its remaining work.

Try It: Early Exit from the Inner Loop

The inner loop stops as soon as it sees the number 3, but the outer loop continues.

What this code does: For each of three outer values the inner loop starts counting from 1. When the inner counter reaches 3 it breaks, so only 1 and 2 are printed for every outer iteration.
for outer in range(1, 4):
    print("Outer =", outer, end=" → ")
    for inner in range(1, 6):
        if inner == 3:
            break
        print(inner, end=" ")
    print()

Try It: Skipping Values with continue

The inner loop skips even numbers and prints only the odd ones.

What this code does: For each of three rows the inner loop examines the numbers 1–6 but uses continue to skip the even values, printing only the odd numbers.
for row in range(1, 4):
    print(f"Row {row}:", end=" ")
    for n in range(1, 7):
        if n % 2 == 0:
            continue
        print(n, end=" ")
    print()

Practical Tips for Nested Loops

Nested loops can solve many problems, but their structure should remain easy to follow. Before adding another level, identify what each loop represents and whether the task genuinely requires repeated work inside repeated work. Pay attention to indentation, counter updates, and the total number of iterations, especially when working with larger collections or running examples in a browser.

  • Always ask whether a nested loop is really needed; sometimes a single loop or a built-in function is clearer and faster.
  • Keep the iteration counts small while you are learning, especially in the browser.
  • Give the loop variables meaningful names (row/col, i/j, outer/inner) so the purpose of each level is obvious.
  • Remember that break and continue apply only to the loop that directly contains them.
  • When the number of combinations grows quickly (for example two loops each running 100 times), consider whether a different algorithm would be better.

Key Takeaways

Nested loops provide a straightforward way to handle tasks that involve multiple dimensions or repeated groups of information. The key is to understand the relationship between the outer and inner loops and follow the order in which their iterations run. Practice with small grids and patterns first, then apply the same structure to tables, combinations, and other problems involving repeated operations.

  • A nested loop is a loop placed inside another loop; the inner loop runs fully for every iteration of the outer loop.
  • Common uses include grids, tables, patterns, and generating combinations.
  • You can nest for and while loops in any combination.
  • break and continue affect only the innermost loop that contains them.
  • In the browser keep both outer and inner limits modest so the page remains responsive.

Frequently Asked Questions

Nested loops often raise questions about execution order, indentation, performance, and how one loop affects another. The answers below explain common situations you may encounter while writing or debugging nested loops in Python. Use them as a quick reference when adapting the examples to your own programs or working with larger sets of data.

How many levels of nesting are allowed?

Python does not impose a strict limit, but readability suffers quickly beyond two or three levels. If you need deeper nesting, consider extracting the inner logic into a separate function.

Does break leave both the inner and the outer loop?

No. break terminates only the loop that directly contains it (the innermost one). The outer loop continues with its next iteration. To leave several levels you can use a flag variable or place the loops inside a function and use return.

Can I put a while loop inside a for loop?

Yes. Any combination is legal: for inside for, while inside while, for inside while, or while inside for. Choose the form that expresses the logic most clearly.

Why do the examples use such small ranges?

This tutorial runs Python inside the browser. Nested loops multiply the number of iterations, so even moderate limits can freeze the tab. The examples therefore stay at 3–5 iterations per level.

When should I avoid nested loops?

When a clearer or more efficient alternative exists— for example using zip(), enumerate(), list comprehensions, or a library function that already solves the problem. Nested loops are powerful but can become hard to read and slow if the ranges grow large.

How can I visualise what a nested loop is doing?

Add temporary print statements that show the current values of the outer and inner counters. Watching the order in which the numbers appear is often the fastest way to understand the flow.

What is the time complexity of two nested loops?

If the outer loop runs n times and the inner loop runs m times, the body executes n × m times. When both limits are the same size n, the complexity is O(n²). That is why keeping the limits small matters in interactive examples.

Can a nested loop contain an if statement?

Yes. Conditionals are frequently placed inside the inner loop (or between the two loops) to decide what to print, when to break, or when to continue.

Ready for the next step?Start working with Python’s most versatile data structure.
Next: Lists & List Methods →