|
| 1 | +--- |
| 2 | +title: Tutorial on nested loops |
| 3 | +date: 2025-05-08 |
| 4 | +tags: |
| 5 | + - Notes |
| 6 | + - IIT Madras |
| 7 | +excludeSearch: false |
| 8 | +weight: 40.2 |
| 9 | +--- |
| 10 | + |
| 11 | +Okay, let's dive into **nested `for` loops**! 😊🔄 |
| 12 | + |
| 13 | +You already know that loops are super helpful for making the computer **repeat actions**. The `for` loop is great for this, especially when you're stepping through items in a sequence like a string or a list, or when you know you need to do something a specific number of times using `range()`. |
| 14 | + |
| 15 | +**What are Nested Loops?** 🤔📦📦 |
| 16 | +"Nested" just means putting one loop **inside** another loop. Think of it like having a main task (the outer loop) that requires doing another, smaller task (the inner loop) multiple times as part of the main task. |
| 17 | + |
| 18 | +According to the sources, you can nest `while` and `for` loops in **any combination**: |
| 19 | +* `for` inside `for` |
| 20 | +* `while` inside `while` |
| 21 | +* `for` inside `while` |
| 22 | +* `while` inside `for` |
| 23 | + |
| 24 | +Our focus here is on **`for` inside `for`**. |
| 25 | + |
| 26 | +**How Nested `for` Loops Work** ⚙️🚦 |
| 27 | +When you have a `for` loop inside another `for` loop, the execution flow is like this: |
| 28 | + |
| 29 | +```python |
| 30 | +# Outer loop starts 🔄 |
| 31 | +for <outer_variable> in <outer_sequence>: |
| 32 | + # Code inside the outer loop's body |
| 33 | + # This includes the entire inner loop 👇 |
| 34 | + |
| 35 | + # Inner loop starts ✨ |
| 36 | + for <inner_variable> in <inner_sequence>: |
| 37 | + # Code inside the inner loop's body |
| 38 | + # This code runs for EACH iteration of the inner loop |
| 39 | + pass # Replace with actual code |
| 40 | + |
| 41 | + # Code in the outer loop's body that runs AFTER the inner loop finishes |
| 42 | + pass # Replace with actual code |
| 43 | + |
| 44 | +# Code outside both loops (runs after the outer loop finishes) |
| 45 | +``` |
| 46 | +Remember that **indentation** is super important in Python to show what code belongs to which loop. The code inside the inner loop is indented further than the inner loop's `for` line, and the inner loop's `for` line (and any other code in the outer loop's body) is indented under the outer loop's `for` line. |
| 47 | + |
| 48 | +The sources explain the execution like this: |
| 49 | +1. The **outer loop** starts. It takes the *first* item from the `<outer_sequence>` and assigns it to the `<outer_variable>`. |
| 50 | +2. The computer then goes into the outer loop's body and reaches the **inner loop**. |
| 51 | +3. The **inner loop** starts running, just like a regular `for` loop. It iterates through *all* the items in the `<inner_sequence>`. For *each* item in the `<inner_sequence>`, it assigns it to the `<inner_variable>` and runs the inner loop's body. |
| 52 | +4. Once the **inner loop has completed all its iterations** for the *current* item of the outer loop, the computer continues with any remaining code in the outer loop's body (the code indented at the same level as the inner `for` statement). |
| 53 | +5. Then, the **outer loop** goes back to its header to get the *next* item from the `<outer_sequence>`. |
| 54 | +6. Steps 2-5 repeat. For *every single item* in the outer sequence, the **entire inner loop runs from start to finish**. |
| 55 | +7. This continues until the outer loop has processed all its items. |
| 56 | + |
| 57 | +**Example from Sources (VIBGYOR)** 🌈🔁 |
| 58 | +One source gives a great example using a string `s = "VIBGYOR"` and nested `for` loops with `range(7)`. This is like seeing every possible combination of selecting two colours from the list (even picking the same colour twice). |
| 59 | + |
| 60 | +```python |
| 61 | +s = "VIBGYOR" |
| 62 | + |
| 63 | +for i in range(7): # Outer loop: i goes from 0 to 6 (representing the index of the first colour) |
| 64 | + # For each value of i... |
| 65 | + for j in range(7): # Inner loop: j goes from 0 to 6 (representing the index of the second colour) |
| 66 | + # ...the ENTIRE inner loop runs. |
| 67 | + # Inside the inner loop, we print the combination of the colour at index i and the colour at index j |
| 68 | + print(f"{s[i]} {s[j]}") # Printing combination based on indices |
| 69 | +``` |
| 70 | + |
| 71 | +Let's trace a bit, as shown in the source: |
| 72 | +* When `i` is `0` (the first iteration of the outer loop), `s[i]` is 'V'. |
| 73 | +* The inner loop starts. `j` goes from `0` to `6`. |
| 74 | + * `j` is `0`: prints "V V" |
| 75 | + * `j` is `1`: prints "V I" |
| 76 | + * `j` is `2`: prints "V B" |
| 77 | + * ... |
| 78 | + * `j` is `6`: prints "V R" |
| 79 | +* The inner loop finishes for `i=0`. |
| 80 | +* The outer loop moves to its next iteration. `i` becomes `1` (now `s[i]` is 'I'). |
| 81 | +* The inner loop starts *again* from the beginning. `j` goes from `0` to `6`. |
| 82 | + * `j` is `0`: prints "I V" |
| 83 | + * `j` is `1`: prints "I I" |
| 84 | + * ... |
| 85 | + * `j` is `6`: prints "I R" |
| 86 | +* This pattern continues until `i` goes through all values up to 6, and for each `i`, `j` completes its full run from 0 to 6. |
| 87 | + |
| 88 | +This is powerful for tasks like generating combinations, working with tables or matrices (lists of lists). |
| 89 | + |
| 90 | +**Other Concepts with Nested Loops:** |
| 91 | +* **`break` and `continue`:** These can be used in nested loops. Crucially, a `break` statement inside the **inner loop** will **only** exit the inner loop. The outer loop will then continue its next iteration. |
| 92 | +* **`else` Clause:** Like single loops, nested loops can have an `else` clause. An `else` block on a loop executes *only* if the loop finishes normally (without hitting a `break`). |
| 93 | + |
| 94 | +Nested loops might look a "little complex" at first, but the sources reassure us that it's "not at all complicated" and you'll master it with time. Taking it slow, being patient, maybe using a pen and paper to diagram what's happening with the variables can make things easier. As with learning anything new, especially coding, **practice makes one perfect**. |
| 95 | + |
| 96 | +Keep practicing and happy coding! 👍💻 |
0 commit comments