Loop Variable Mutation and States

🏷️ Loops and Iteration / The For Loop

🧠 Context Introduction

When you write a for loop, Python creates a variable that changes its value with each iteration. This is called the loop variable. Understanding how this variable behaves—how it mutates (changes) and what state it holds—is essential for writing predictable and bug-free code. Engineers often assume the loop variable works a certain way, but Python has some subtle behaviors that can surprise you.


⚙️ What Is a Loop Variable?

A loop variable is the temporary name you assign to each element as you iterate over a sequence (like a list, string, or range). It gets a new value at the start of every loop cycle.

Example (inline): - You write: for item in ["a", "b", "c"]: - The loop variable item starts as "a", then becomes "b", then "c". - After the loop ends, item retains its last value: "c".


🕵️ Key Behaviors of Loop Variable Mutation

  • The loop variable is reassigned each iteration. It does not "accumulate" or merge values—it simply takes the next element from the sequence.
  • You can mutate the loop variable inside the loop, but this does not affect the original sequence. The variable is just a copy of the reference.
  • After the loop finishes, the loop variable still exists and holds the last value it was assigned. This is different from some other languages where the variable goes out of scope.

Example (inline): - Code: for x in [1, 2, 3]: x = x * 2 - Inside the loop, x becomes 2, then 4, then 6. - The original list [1, 2, 3] is unchanged. - After the loop, x is 6.


📊 Comparison Table: Loop Variable vs. Sequence Elements

Aspect Loop Variable Sequence Element
Purpose Temporary holder for current iteration Original data source
Mutability Can be reassigned freely Not affected by loop variable changes
Lifetime Exists after loop ends Exists independently
Scope Accessible outside the loop block Accessible only if referenced by name

🛠️ Common Pitfall: Modifying the Loop Variable Thinking It Changes the List

A frequent mistake is assuming that changing the loop variable will also change the original list. This is not true for immutable elements like integers or strings.

Example (inline): - Code: numbers = [1, 2, 3]; for n in numbers: n = n + 1 - You might expect numbers to become [2, 3, 4], but it stays [1, 2, 3]. - The variable n is just a copy of the reference; reassigning n does not write back to the list.

To actually modify the list, you need to use the index: - Code: for i in range(len(numbers)): numbers[i] = numbers[i] + 1 - Now numbers becomes [2, 3, 4].


🧩 State of the Loop Variable After the Loop

Python does not clean up the loop variable after the loop ends. This can lead to bugs if you accidentally reuse the variable name later.

Example (inline): - Code: for i in range(5): pass; print(i) - Output: 4 - The variable i is still available and holds 4.

Best practice: Avoid relying on the loop variable after the loop unless you explicitly need its final value. If you do need it, consider using a separate variable to store the result.


🔄 Mutation with Mutable Objects (Lists, Dictionaries)

If the loop variable refers to a mutable object (like a list or dictionary), modifying the object's contents will affect the original sequence.

Example (inline): - Code: matrix = [[1, 2], [3, 4]]; for row in matrix: row.append(0) - The loop variable row is a reference to each inner list. - Calling row.append(0) modifies the actual inner list. - After the loop, matrix becomes [[1, 2, 0], [3, 4, 0]].

Key distinction: - Reassigning the loop variable (e.g., row = [5, 6]) does not affect the original. - Mutating the object (e.g., row.append(7)) does affect the original.


✅ Summary of Best Practices

  • Treat the loop variable as a read-only reference unless you are intentionally mutating a mutable object.
  • If you need to modify a list while iterating, use index-based loops or create a new list.
  • Do not depend on the loop variable's value after the loop unless you have explicitly stored it.
  • Be aware that the loop variable persists after the loop ends—rename or reset it if needed to avoid confusion.

🧪 Quick Self-Check

  • What is the value of x after this code runs: for x in [10, 20, 30]: pass
  • Answer: 30
  • Does for item in items: item = 0 change the original list items?
  • Answer: No, it only reassigns the loop variable.
  • If items is a list of lists, does for sublist in items: sublist.clear() affect items?
  • Answer: Yes, because sublist is a reference to the mutable inner list.

Understanding loop variable mutation and states helps you write loops that behave exactly as you expect—no surprises, no hidden bugs. Keep these principles in mind as you work with iteration in Python.


This topic shows how the loop variable changes during iteration and how modifying it inside the loop affects program behavior.


🧪 Example 1: Loop variable takes each value from the sequence

This example shows the loop variable automatically updating to each item in the list.

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

📤 Output: red green blue


🧪 Example 2: Loop variable resets each iteration

This example shows that assigning a new value to the loop variable does not change the next iteration's value.

numbers = [10, 20, 30]
for num in numbers:
    num = 99
    print(num)

📤 Output: 99 99 99


🧪 Example 3: Loop variable mutation does not affect the original list

This example shows that changing the loop variable does not modify the original sequence.

values = [1, 2, 3]
for v in values:
    v = v * 10
    print(v)
print(values)

📤 Output: 10 20 30 [1, 2, 3]


🧪 Example 4: Using loop variable state to accumulate a result

This example shows how to use the loop variable's current value to build a running total.

scores = [85, 92, 78, 95]
total = 0
for score in scores:
    total = total + score
    print("Current total:", total)

📤 Output: Current total: 85 Current total: 177 Current total: 255 Current total: 350


🧪 Example 5: Loop variable state tracking with enumerate

This example shows how to track both the index and value using the loop variable's state.

tasks = ["design", "code", "test"]
for index, task in enumerate(tasks):
    state = "in progress"
    print(f"Task {index + 1}: {task} - {state}")

📤 Output: Task 1: design - in progress Task 2: code - in progress Task 3: test - in progress


🧪 Example 6: Loop variable state used for conditional logic

This example shows how the loop variable's current state can control decisions inside the loop.

readings = [22, 25, 30, 28, 35]
for temp in readings:
    if temp > 30:
        print(f"Warning: {temp}°C exceeds limit")
    else:
        print(f"OK: {temp}°C")

📤 Output: OK: 22°C OK: 25°C OK: 30°C Warning: 35°C OK: 28°C


📊 Comparison Table: Loop Variable Behavior

Concept What Happens Example Effect
Normal iteration Variable takes each sequence value for x in [1,2,3]: print(x) → 1 2 3
Variable mutation Changing variable does not affect next iteration x = 99 inside loop → next iteration still gets original value
Original list unchanged Loop variable is a copy, not a reference Modifying v does not change the source list
State accumulation Variable value used to build results total = total + score tracks running sum
Index tracking enumerate() provides position and value for i, val in enumerate(list) gives both states

🧠 Context Introduction

When you write a for loop, Python creates a variable that changes its value with each iteration. This is called the loop variable. Understanding how this variable behaves—how it mutates (changes) and what state it holds—is essential for writing predictable and bug-free code. Engineers often assume the loop variable works a certain way, but Python has some subtle behaviors that can surprise you.


⚙️ What Is a Loop Variable?

A loop variable is the temporary name you assign to each element as you iterate over a sequence (like a list, string, or range). It gets a new value at the start of every loop cycle.

Example (inline): - You write: for item in ["a", "b", "c"]: - The loop variable item starts as "a", then becomes "b", then "c". - After the loop ends, item retains its last value: "c".


🕵️ Key Behaviors of Loop Variable Mutation

  • The loop variable is reassigned each iteration. It does not "accumulate" or merge values—it simply takes the next element from the sequence.
  • You can mutate the loop variable inside the loop, but this does not affect the original sequence. The variable is just a copy of the reference.
  • After the loop finishes, the loop variable still exists and holds the last value it was assigned. This is different from some other languages where the variable goes out of scope.

Example (inline): - Code: for x in [1, 2, 3]: x = x * 2 - Inside the loop, x becomes 2, then 4, then 6. - The original list [1, 2, 3] is unchanged. - After the loop, x is 6.


📊 Comparison Table: Loop Variable vs. Sequence Elements

Aspect Loop Variable Sequence Element
Purpose Temporary holder for current iteration Original data source
Mutability Can be reassigned freely Not affected by loop variable changes
Lifetime Exists after loop ends Exists independently
Scope Accessible outside the loop block Accessible only if referenced by name

🛠️ Common Pitfall: Modifying the Loop Variable Thinking It Changes the List

A frequent mistake is assuming that changing the loop variable will also change the original list. This is not true for immutable elements like integers or strings.

Example (inline): - Code: numbers = [1, 2, 3]; for n in numbers: n = n + 1 - You might expect numbers to become [2, 3, 4], but it stays [1, 2, 3]. - The variable n is just a copy of the reference; reassigning n does not write back to the list.

To actually modify the list, you need to use the index: - Code: for i in range(len(numbers)): numbers[i] = numbers[i] + 1 - Now numbers becomes [2, 3, 4].


🧩 State of the Loop Variable After the Loop

Python does not clean up the loop variable after the loop ends. This can lead to bugs if you accidentally reuse the variable name later.

Example (inline): - Code: for i in range(5): pass; print(i) - Output: 4 - The variable i is still available and holds 4.

Best practice: Avoid relying on the loop variable after the loop unless you explicitly need its final value. If you do need it, consider using a separate variable to store the result.


🔄 Mutation with Mutable Objects (Lists, Dictionaries)

If the loop variable refers to a mutable object (like a list or dictionary), modifying the object's contents will affect the original sequence.

Example (inline): - Code: matrix = [[1, 2], [3, 4]]; for row in matrix: row.append(0) - The loop variable row is a reference to each inner list. - Calling row.append(0) modifies the actual inner list. - After the loop, matrix becomes [[1, 2, 0], [3, 4, 0]].

Key distinction: - Reassigning the loop variable (e.g., row = [5, 6]) does not affect the original. - Mutating the object (e.g., row.append(7)) does affect the original.


✅ Summary of Best Practices

  • Treat the loop variable as a read-only reference unless you are intentionally mutating a mutable object.
  • If you need to modify a list while iterating, use index-based loops or create a new list.
  • Do not depend on the loop variable's value after the loop unless you have explicitly stored it.
  • Be aware that the loop variable persists after the loop ends—rename or reset it if needed to avoid confusion.

🧪 Quick Self-Check

  • What is the value of x after this code runs: for x in [10, 20, 30]: pass
  • Answer: 30
  • Does for item in items: item = 0 change the original list items?
  • Answer: No, it only reassigns the loop variable.
  • If items is a list of lists, does for sublist in items: sublist.clear() affect items?
  • Answer: Yes, because sublist is a reference to the mutable inner list.

Understanding loop variable mutation and states helps you write loops that behave exactly as you expect—no surprises, no hidden bugs. Keep these principles in mind as you work with iteration in Python.

Interactive Views

You are currently in 📚 All-in-One mode. Use the tabs at the top to switch to 📖 Theory Only or 💻 Code Only views.

This topic shows how the loop variable changes during iteration and how modifying it inside the loop affects program behavior.


🧪 Example 1: Loop variable takes each value from the sequence

This example shows the loop variable automatically updating to each item in the list.

colors = ["red", "green", "blue"]
for color in colors:
    print(color)

📤 Output: red green blue


🧪 Example 2: Loop variable resets each iteration

This example shows that assigning a new value to the loop variable does not change the next iteration's value.

numbers = [10, 20, 30]
for num in numbers:
    num = 99
    print(num)

📤 Output: 99 99 99


🧪 Example 3: Loop variable mutation does not affect the original list

This example shows that changing the loop variable does not modify the original sequence.

values = [1, 2, 3]
for v in values:
    v = v * 10
    print(v)
print(values)

📤 Output: 10 20 30 [1, 2, 3]


🧪 Example 4: Using loop variable state to accumulate a result

This example shows how to use the loop variable's current value to build a running total.

scores = [85, 92, 78, 95]
total = 0
for score in scores:
    total = total + score
    print("Current total:", total)

📤 Output: Current total: 85 Current total: 177 Current total: 255 Current total: 350


🧪 Example 5: Loop variable state tracking with enumerate

This example shows how to track both the index and value using the loop variable's state.

tasks = ["design", "code", "test"]
for index, task in enumerate(tasks):
    state = "in progress"
    print(f"Task {index + 1}: {task} - {state}")

📤 Output: Task 1: design - in progress Task 2: code - in progress Task 3: test - in progress


🧪 Example 6: Loop variable state used for conditional logic

This example shows how the loop variable's current state can control decisions inside the loop.

readings = [22, 25, 30, 28, 35]
for temp in readings:
    if temp > 30:
        print(f"Warning: {temp}°C exceeds limit")
    else:
        print(f"OK: {temp}°C")

📤 Output: OK: 22°C OK: 25°C OK: 30°C Warning: 35°C OK: 28°C


📊 Comparison Table: Loop Variable Behavior

Concept What Happens Example Effect
Normal iteration Variable takes each sequence value for x in [1,2,3]: print(x) → 1 2 3
Variable mutation Changing variable does not affect next iteration x = 99 inside loop → next iteration still gets original value
Original list unchanged Loop variable is a copy, not a reference Modifying v does not change the source list
State accumulation Variable value used to build results total = total + score tracks running sum
Index tracking enumerate() provides position and value for i, val in enumerate(list) gives both states