What is really happening?
Step 1 – Initial list
arr = [1, 2, 3]
The list has three values.
Step 2 – Loop execution
for i in arr:
Python takes each value one by one and stores it in i.
| Iteration | i value | i * 10 |
|---|---|---|
| 1st | 1 | 10 |
| 2nd | 2 | 20 |
| 3rd | 3 | 30 |
Step 3 – The mistake
i = i * 10
Here you are changing only i, not the list.
i is just a copy, not a reference to arr elements.
So:
arr[0] stays 1
arr[1] stays 2
arr[2] stays 3
Final Result
print(arr)
Output:
[1, 2, 3]
Memory visualization (easy way)
Think like this:
arr → [1, 2, 3]i → 1 → 10 (dies)i → 2 → 20 (dies)i → 3 → 30 (dies)
i changes, but arr never changes.
Correct way to modify the list
Using index:
for i in range(len(arr)):arr[i] = arr[i] * 10
Or Pythonic:
arr = [x * 10 for x in arr]
Interview one-liner:
In Python, loop variables hold values, not references for immutable types like integers.


0 Comments:
Post a Comment