Python Loops
Estimated reading: 3 minutes 266 views

Python Nested Loops – Learn with Grids, Patterns, and Matrices

Introduction – Why Learn Nested Loops?

In programming, it’s common to encounter tasks that require comparing elements across multiple sequences, generating grids, or building complex tables. That’s where nested loops come in handy.

A nested loop is a loop inside another loop. Python supports nesting for, while, or even mixed loops, enabling powerful iterations across multiple dimensions.

In this guide, you’ll learn:

  • How nested for and while loops work
  • Real-world examples: patterns, grids, and matrix operations
  • Nested break and continue handling
  • Best practices and performance considerations

Syntax of Nested Loops

Nested for Loop Syntax

for outer_var in outer_iterable:
    for inner_var in inner_iterable:
        # code block

Nested while Loop Syntax

while condition1:
    while condition2:
        # code block

Example 1: Multiplication Table (3×3)

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

Output:

1 × 1 = 1
1 × 2 = 2
1 × 3 = 3
2 × 1 = 2
...
3 × 3 = 9

Explanation:
For each value of i, the inner loop iterates through values of j.


Example 2: Printing a Pattern (Right-Angled Triangle)

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

Output:

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

Use Case: Pattern generation, a common interview task.


Example 3: Nested Loop With break

for i in range(3):
    for j in range(3):
        if j == 1:
            break
        print(f"i={i}, j={j}")

Output:

i=0, j=0
i=1, j=0
i=2, j=0

Explanation: The inner loop breaks when j == 1.


Example 4: Traversing a 2D List (Matrix)

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

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

Output:

1 2 3
4 5 6
7 8 9

Use Case: Processing 2D arrays or CSV-style data.


Nested while Loop Example

i = 1
while i <= 3:
    j = 1
    while j <= 2:
        print(f"i={i}, j={j}")
        j += 1
    i += 1

Common Pitfalls with Nested Loops

PitfallTip to Avoid
Too many nested levelsUse functions or recursion to simplify
Infinite inner loopEnsure loop conditions update correctly
Poor performanceAvoid unnecessary nested iterations (O(n²+))
Misusing break or continueRemember: these only affect the current loop

Best Practices

  • Keep nesting to 2 or 3 levels max for readability
  • Extract inner loop logic into helper functions
  • Use list comprehensions for simple nested iterations
  • Use enumerate() or zip() when indexing is needed

Summary – Key Takeaways

  • Nested loops are loops within loops, useful for multi-dimensional data and complex iteration patterns
  • You can nest both for and while loops
  • Control flow tools like break and continue apply only to the nearest enclosing loop
  • Structure your code clearly and keep an eye on performance

FAQ Section

What is a nested loop?

A loop inside another loop. Commonly used for 2D arrays or pattern generation.

Can I nest a for loop inside a while loop?

Yes. Python allows any loop combination:

while condition:
    for x in iterable:
        # code

Do break and continue affect both loops?

No. They only affect the innermost loop. Use flags or functions to control outer loops.

When should I avoid nested loops?

Avoid them when performance is a concern or when the logic becomes too complex. Consider using sets, maps, or algorithms instead.


Share Now :
Share

Python Nested Loops

Or Copy Link

CONTENTS
Scroll to Top