Step-by-Step Explanation
Step 1 — Original List
data = [100, 200, 300]A list with three numbers.
Step 2 — Loop Starts
for i in data:i takes copy of each value, not the actual list element.
Iterations:
-
First → i = 100
-
Second → i = 200
-
Third → i = 300
Step 3 — Modify i
i += 50This changes only the temporary variable i, not the list.
So internally:
-
100 → 150 (temporary)
-
200 → 250 (temporary)
-
300 → 350 (temporary)
But data list is unchanged.
Step 4 — Print List
print(data)Since the original list was never modified:
[100, 200, 300]Important Concept (Interview Question)
Changing loop variable does NOT change list elements.
Because:
i is a separate variable
-
It does not point back to list index
How to Actually Modify the List
Method 1 — Using Index
Output:
[150, 250, 350]One-Line Pythonic Way
Golden Rule (Very Important)
Loop variable changes value
List element stays same
Unless you use index.


0 Comments:
Post a Comment