π 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
andwhile
loops work - Real-world examples: patterns, grids, and matrix operations
- Nested
break
andcontinue
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
Pitfall | Tip to Avoid |
---|---|
Too many nested levels | Use functions or recursion to simplify |
Infinite inner loop | Ensure loop conditions update correctly |
Poor performance | Avoid unnecessary nested iterations (O(nΒ²+)) |
Misusing break or continue | Remember: 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()
orzip()
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
andwhile
loops - Control flow tools like
break
andcontinue
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 :