Nested Loops in Python – Syntax, Examples & Usage

Introduction

A nested loop is simply a loop placed inside another loop. The outer loop controls how many times the inner loop runs. Nested loops are commonly used for working with tables, matrices, patterns, grids, game boards, and data processing tasks.

In this tutorial, you will learn what nested loops are, their syntax, examples, real-life applications, common mistakes, interview questions, and best practices.

What are Nested Loops?

A nested loop is a loop inside another loop.

The outer loop executes first, and for each iteration of the outer loop, the inner loop executes completely.

Example:


for i in range(3):
    for j in range(2):
        print(i, j)

Output:

0 0
0 1
1 0
1 1
2 0
2 1

Explanation

  • The outer loop runs 3 times.
  • For each outer loop iteration, the inner loop runs 2 times.
  • Total executions = 3 × 2 = 6.

Why Use Nested Loops?

Nested loops are useful when:

  • Working with rows and columns.
  • Printing patterns.
  • Processing matrices.
  • Generating multiplication tables.
  • Comparing data sets.
  • Building games and simulations.

They help solve problems that require multiple levels of iteration.

Syntax

Nested For Loop


for outer_variable in outer_sequence:
    for inner_variable in inner_sequence:
        # code block

Nested While Loop


while condition1:   
    while condition2:
        # code block

Mixed Nested Loop


for i in range(3):
    while condition:
        # code block

Python allows any loop type to be nested inside another.

How Nested Loops Work

Consider the following example:


for i in range(2):
    for j in range(3):
        print(i, j)

Output:

0 0
0 1
0 2
1 0
1 1
1 2

Execution Process

First Outer Iteration


i = 0

Inner loop runs:

0 0
0 1
0 2

Second Outer Iteration


i = 1

Inner loop runs again:

1 0
1 1
1 2

The inner loop completes fully during each outer iteration.

Nested For Loop Example


for row in range(3):
    for column in range(3):
        print("*", end=" ")
   
    print()

Output:

* * *
* * *
* * *

This creates a simple grid pattern.

Nested While Loop Example


i = 1
while i <= 3:
    j = 1
    while j <= 2:
        print(i, j)
        j += 1
    i += 1

Output:

1 1
1 2
2 1
2 2
3 1
3 2

Nested Loop with Lists


students = ["John", "Emma"]
subjects = ["Math", "Science"]
for student in students:
    for subject in subjects:
        print(student, "-", subject)

Output:

John – Math
John – Science
Emma – Math
Emma – Science

Each student is paired with each subject.

Multiplication Table Example


for i in range(1, 6):
    for j in range(1, 6):
        print(i * j, end="\t")
    print()

Output:

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

Nested loops are commonly used for table generation.

Star Pattern Example


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

Output:

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

This is a popular beginner exercise.

Reverse Star Pattern


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

Output:

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

Number Pattern Example


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

Nested Loop with Break

The break statement only exits the innermost loop.

Example:


for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(i, j)

Output:

0 0
1 0
2 0

Only the inner loop stops.

Nested Loop with Continue

Example:


for i in range(3):
    for j in range(3):
        if j == 1:
            continue
        print(i, j)

Output:

0 0
0 2
1 0
1 2
2 0
2 2

The value 1 is skipped in the inner loop.

Real-Life Examples:

1. Student Attendance System


classes = ["Class A", "Class B"]
students = ["John", "Emma"]
for classroom in classes:
    for student in students:
        print(classroom, "-", student)

Output:

Class A – John
Class A – Emma
Class B – John
Class B – Emma

Schools often process students class-wise.

2. E-Commerce Product Variations


colors = ["Red", "Blue"]
sizes = ["M", "L"]
for color in colors:
    for size in sizes:
        print(color, size)

Output:

Red M
Red L
Blue M
Blue L

Online stores generate product combinations using nested loops.

3. Seating Arrangement


rows = 3
seats = 4
for row in range(1, rows + 1):
    for seat in range(1, seats + 1):
        print(f"Row {row} Seat {seat}")

Output:

Row 1 Seat 1
Row 1 Seat 2 …

Movie theaters and airlines use similar logic.

4. Game Board


for row in range(3):
    for column in range(3):
        print("[ ]", end="")
    print()

Output:

[ ][ ][ ]
[ ][ ][ ]
[ ][ ][ ]

Grid-based games often use nested loops.

Advantages of Nested Loops

1. Handles Complex Iterations

Useful when multiple dimensions are involved.

2. Processes Tables and Matrices

Ideal for rows and columns.

3. Generates Patterns Easily

Used extensively in programming exercises.

4. Supports Data Comparison

Can compare elements across collections.

5. Widely Used in Real Applications

Common in games, reports, and data analysis.

Common Mistakes

1. Incorrect Indentation

Incorrect:


for i in range(3):
for j in range(3):
    print(i, j)

Output:

IndentationError

Correct:


for i in range(3):
    for j in range(3):
        print(i, j)

2. Forgetting to Reset Variables

Incorrect:


i = 1
j = 1
while i <= 3:
    while j <= 3:
        print(i, j)
        j += 1
    i += 1

The inner loop won’t restart correctly.

3. Creating Infinite Loops

Incorrect:


while True:
    while True:
        print("Hello")

Without proper exit conditions, both loops run forever.

4. Using Too Many Nested Levels


for a in range(5):
    for b in range(5):
        for c in range(5):
            for d in range(5):
                pass

Deep nesting reduces readability.

5. Confusing Inner and Outer Variables

Incorrect:


for i in range(3):
    for i in range(3):
        print(i)

Use different variable names.

Best Practices

1. Use Meaningful Variable Names


for row in range(5):
    for column in range(5):
        pass

2. Avoid Excessive Nesting

Try to keep nesting levels low.

3. Use Functions for Complex Logic

Break large nested loops into smaller functions.

4. Keep Code Readable

Use proper indentation and comments.

5. Optimize Performance

Remember:


Outer Loop × Inner Loop = Total Iterations

For example:


100 × 100 = 10,000 iterations

Large nested loops can impact performance.

Conclusion

Nested loops are a powerful programming technique that allows one loop to run inside another. They are widely used for working with rows and columns, generating patterns, processing matrices, creating multiplication tables, building game boards, and handling complex data structures.

Although nested loops are extremely useful, developers should use them carefully because they can increase execution time when processing large datasets.

Related Python Tutorials