Python Nested Loops Explained for Beginners (With Simple Examples)

Python Nested Loops Explained for Beginners (With Simple Examples)

Python Nested Loops Explained for Beginners (With Simple Examples)

Introduction

In the previous post, we learned about break, continue, and pass. Now let's move forward and understand Nested Loops.

Nested loops are used when we need to repeat a task inside another repetition. Simply put — a loop inside another loop.

---

What is a Nested Loop?

A nested loop is a loop placed inside another loop. The inner loop runs completely every time the outer loop runs once.

Outer Loop → Controls main repetition
Inner Loop → Runs fully for each outer loop cycle
---

Basic Example

for i in range(3):        # Outer loop
    for j in range(2):    # Inner loop
        print("i =", i, "j =", j)

Here:

  • Outer loop runs 3 times
  • Inner loop runs 2 times each time
  • Total execution = 3 × 2 = 6 times
---

Understanding the Flow

When i = 0 → j runs 0,1
When i = 1 → j runs 0,1
When i = 2 → j runs 0,1

This is why nested loops multiply the number of operations.

---

Example: Printing a Square Pattern

for i in range(4):
    for j in range(4):
        print("*", end=" ")
    print()

Output:

* * * *
* * * *
* * * *
* * * *
---

Example: Printing a Triangle Pattern

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

Output:

*
* *
* * *
* * * *
---

Real-Life Example (Working with 2D Lists)

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

for row in matrix:
    for item in row:
        print(item, end=" ")
    print()

Nested loops are used to process rows and columns in tables, matrices, and datasets.

---

Why Nested Loops Are Important?

  • Used in pattern-based coding problems
  • Helpful in matrix and table operations
  • Common in real-world data processing
  • Very important for logic building
---

Important Rule to Remember

Total Iterations = Outer Loop × Inner Loop
---

Common Beginner Mistakes

  • Wrong indentation
  • Confusing outer and inner loop roles
  • Forgetting inner loop runs completely each time
---

What You Learned in This Post

  • What nested loops are
  • How loops run inside each other
  • Printing patterns using nested loops
  • Working with 2D data structures
---

What’s Next?

Now that you understand loops deeply, we will start working with Strings in Python.

Next Post: Python Strings Explained for Beginners

---

👋 About the Author

Ayush Gupta
MSc AI/ML Student | Machine Learning & Python Enthusiast

📧 Email: aygupta9898@gmail.com

Comments

Popular posts from this blog

What is Programming? Simple Explanation for Beginners

What is Python? Why Learn Python for Beginners

How to Install Python on Windows and Mac (Step-by-Step Guide)