- What nested for loops are ā a loop inside another loop
- How to write them ā correct syntax and structure
- How they execute ā understanding the flow
- Creating star patterns ā classic beginner exercise
- Number patterns ā building logical sequences
- Multiplication tables ā a practical use case
- Working with matrices ā processing 2D data
- Common mistakes ā and how to avoid them
Welcome: Why Nested Loops?
Think of it this way: Imagine you're arranging books on shelves. The outer loop goes through each shelf. The inner loop goes through each book on that shelf. You can't arrange books without knowing both which shelf you're on and which book you're placing. That's exactly what nested loops do!
A nested for loop is a for loop inside another for loop. This powerful concept lets you work with multi-dimensional data ā like tables, grids, or matrices. When you need to repeat an action multiple times within another repeated action, nested loops are your solution.
š” Key insight: The inner loop completes all its iterations for each single iteration of the outer loop. Think of it like a clock: the outer loop is the hour hand (slow), the inner loop is the minute hand (fast). The minute hand completes a full cycle for each hour.
Step 1: Understanding the Concept
What's Really Happening?
Before we write code, let's understand the concept with a real-world analogy.
Imagine you have 3 classrooms, each with 4 students. You want to say "Hello" to every student in every classroom. Outer loop: Go to each classroom (3 times) Inner loop: Say "Hello" to each student in that classroom (4 times) Total greetings = 3 Ć 4 = 12
ā Quick Check: If you have 5 classrooms with 6 students each, how many total greetings? (Answer: 5 Ć 6 = 30)
Step 2: Syntax & Structure
How Do You Write One?
The syntax is simple ā just put one for loop inside another:
for outer_variable in outer_sequence:
for inner_variable in inner_sequence:
# This runs for each outer iteration
print(outer_variable, inner_variable)
Breakdown:
- Outer loop ā controls the major iteration (rows)
- Inner loop ā runs completely for each outer iteration (columns)
- Indentation ā inner loop must be indented inside the outer loop
ā
Quick Check: What's wrong with: for i in range(3): for j in range(3): print(i, j) (Answer: Missing colon after the inner for loop)
Step 3: How They Execute
Following the Flow
Let's trace the execution step by step:
for i in range(1, 4): # Outer loop: i = 1, 2, 3
for j in range(1, 4): # Inner loop: j = 1, 2, 3
print(f"({i},{j})", end=" ")
print() # New line after inner loop
# Execution flow:
# 1. i = 1 ā inner loop runs: (1,1), (1,2), (1,3) ā new line
# 2. i = 2 ā inner loop runs: (2,1), (2,2), (2,3) ā new line
# 3. i = 3 ā inner loop runs: (3,1), (3,2), (3,3) ā new line
# Output:
# (1,1) (1,2) (1,3)
# (2,1) (2,2) (2,3)
# (3,1) (3,2) (3,3)
Key insight: The inner loop completes all its iterations before the outer loop moves to the next iteration. This creates a grid pattern!
ā Quick Check: If outer loop runs 4 times and inner loop runs 3 times, how many total inner loop executions? (Answer: 4 Ć 3 = 12)
Step 4: Star Patterns
Creating a Right Triangle of Stars
This is the classic first exercise for nested loops:
rows = 5
for i in range(1, rows + 1): # Outer: controls rows
for j in range(1, i + 1): # Inner: controls columns (stars)
print("*", end="") # Print star on same line
print() # Move to next line
# Output:
# *
# **
# ***
# ****
# *****
Why does this work?
- When
i = 1, the inner loop runs once ā 1 star - When
i = 2, the inner loop runs twice ā 2 stars - When
i = 3, the inner loop runs three times ā 3 stars - Each row has exactly
istars
ā
Quick Check: How would you make an inverted triangle (5 stars, then 4, then 3...)? (Hint: Make the outer loop go backwards: for i in range(rows, 0, -1))
Step 5: Number Patterns
Creating a Number Triangle
Now let's print numbers instead of stars:
rows = 5
for i in range(1, rows + 1):
for j in range(1, i + 1):
print(j, end=" ") # Print numbers 1 to i
print()
# Output:
# 1
# 1 2
# 1 2 3
# 1 2 3 4
# 1 2 3 4 5
What changed? Instead of printing a star, we print the value of j. Since j goes from 1 to i, we get a triangle of numbers. This is a stepping stone to more complex patterns.
ā Quick Check: How would you print a triangle of consecutive numbers (1, 2 3, 4 5 6...)? (Hint: Use a separate counter variable that increments each time)
Step 6: Multiplication Table
Building a Multiplication Table
A practical use case for nested loops:
for i in range(1, 11):
for j in range(1, 11):
print(f"{i * j:4}", end="") # Each number takes 4 spaces
print() # New line after each row
# Output (first few rows):
# 1 2 3 4 5 6 7 8 9 10
# 2 4 6 8 10 12 14 16 18 20
# 3 6 9 12 15 18 21 24 27 30
What's happening:
- Outer loop:
igoes from 1 to 10 (rows) - Inner loop:
jgoes from 1 to 10 (columns) i * jgives the product:4formatting aligns the numbers neatly
Step 7: Working with Matrices
Processing 2D Data
Nested loops are essential for working with matrices (2D lists):
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
# Print the matrix
for row in matrix:
for element in row:
print(element, end=" ")
print()
# Output:
# 1 2 3
# 4 5 6
# 7 8 9
# Calculate sum of all elements
total = 0
for row in matrix:
for element in row:
total += element
print(f"Total sum: {total}")
# Output: Total sum: 45
Real-world applications:
- Image processing (pixels)
- Game development (grids)
- Data analysis (tables)
- Scientific computing (matrices)
Step 8: Common Mistakes to Avoid
Watch Out For These!
ā Mistake 1: Using the Same Variable
Don't reuse the same variable name in both loops:
# WRONG (using 'i' in both loops)
for i in range(3):
for i in range(3): # This will cause problems!
print(i)
# CORRECT (using different variables)
for i in range(3):
for j in range(3):
print(i, j)
ā Mistake 2: Forgetting to Indent
Python uses indentation to define blocks. Incorrect indentation changes the logic:
# WRONG (inner loop not indented)
for i in range(3):
print(i) # Not inside the loop!
# CORRECT (proper indentation)
for i in range(3):
print(i)
ā Mistake 3: Not Resetting Inner Variable
If you're using while loops inside for loops, remember to reset the inner counter:
# WRONG (j keeps increasing)
i = 1
while i <= 3:
j = 1 # ā Important: Reset j here!
while j <= i:
print("*", end="")
j += 1
print()
i += 1
Try It Yourself!
Experiment with nested for loops directly in your browser. Modify the code and see the results in real time.
NESTED FOR LOOP - PRACTICE
========================================
1. SIMPLE GRID (3x3)
(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)
2. STAR PATTERN
*
**
***
****
*****
3. NUMBER TRIANGLE
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
4. MULTIPLICATION TABLE (5x5)
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
5. MATRIX SUM
Total: 45
ā Now try creating your own patterns!
š You've Mastered Nested For Loops!
You understand nested for loop syntax, patterns, multiplication tables, and matrix operations. This is a powerful skill for complex data processing!
Quick Quiz ā Test Your Knowledge
Let's see what you've learned about nested for loops:
for i in range(2): for j in range(2): print(i, j)?Frequently Asked Questions
š¤ How many levels of nested loops should I use?
š§ What is the time complexity of a nested loop?
š Can I nest a for loop inside a while loop?
for loop can be nested inside a while loop, and vice versa. This flexibility allows you to use the best loop type for each level of iteration.
š How do I break out of multiple nested loops?
break statement only exits the innermost loop. To break out of multiple levels, you can use a flag variable or wrap the loops in a function and use return. Alternatively, you can use a for-else construct with a flag.
ā” What's the difference between nested loops and nested comprehensions?
[i*j for i in range(3) for j in range(3)] is a nested list comprehension.
šÆ What's a real-world example of nested loops?
š Where to Go From Here
Now that you've mastered nested for loops, here are the next topics to explore:
š Nested For Loop Examples
Explore more advanced nested for loop examples.
Learn More āā” Break, Continue, Else
Learn how to control loop execution with break and continue.
Learn More āš For vs While
Understand the differences between for and while loops.
Learn More ā