► Overview
Nested loops are loops inside other loops. The inner loop completes all its iterations for each iteration of the outer loop. They’re essential for working with multi-dimensional data like grids, matrices, and tables.
► Real-World Analogy
Think of reading a book:
» Outer loop: For each chapter
» Inner loop: For each page in that chapter
» Result: Read every page of every chapter
► Key Concepts
✓ Inner loop executes completely for each outer loop iteration
✓ Useful for 2D data structures (rows and columns)
✓ Execution time multiplies (outer * inner iterations)
✓ Can nest multiple levels (use carefully)
✓ Common in pattern printing and matrix operations
■ Nested Loop Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# Simple nested loop - multiplication table for i in range(1, 4): for j in range(1, 4): print(f"{i} x {j} = {i*j}") print() # Pattern printing for row in range(5): for col in range(row + 1): print("*", end=" ") print() # Working with 2D list matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] for row in matrix: for num in row: print(num, end=" ") print() Output: 1 x 1 = 1 1 x 2 = 2 1 x 3 = 3 2 x 1 = 2 2 x 2 = 4 2 x 3 = 6 * * * * * * * * * * 1 2 3 4 5 6 7 8 9 ► Important Points ✓ Outer loop controls how many times inner loop runs ✓ Total iterations = outer × inner iterations ✓ Watch out for performance with large loops ✓ Break and continue affect only their immediate loop ✓ Essential for working with tables and grids ► Remember ✓ Inner loop completes fully before outer loop continues ✓ Use descriptive variable names (row, col instead of i, j) ✓ Keep nesting levels reasonable (2-3 max) ✓ Consider performance for large datasets ✓ Useful for matrix operations and pattern printing ■ Practice Challenge 1. Create a 5x5 multiplication table using nested loops 2. Print a right-angled triangle pattern with numbers 3. Find all pairs of numbers from two lists that sum to 10 |
