Step-by-step explanation
1. Initial list
arr = [1, 2, 3]arr is a list with three integers.
2. Loop execution
-
The loop goes through each element of arr.
i is a temporary variable that receives the value of each element — not the reference to the list element.
Iteration by iteration:
| Iteration | i before | i = i * 2 | arr |
|---|---|---|---|
| 1 | 1 | 2 | [1, 2, 3] |
| 2 | 2 | 4 | [1, 2, 3] |
| 3 | 3 | 6 | [1, 2, 3] |
๐ i changes, but arr does not change.
3. Final print
print(arr)Since the list was never modified, the output is:
[1, 2, 3]Why doesn’t the list change?
Because:
i is a copy of the value, not the element inside the list.
-
Reassigning i does not update arr.
This is equivalent to:
✅ Correct way to modify the list
If you want to update the list, use the index:
Output:
[2, 4, 6]Key takeaway
Looping as for i in arr gives you values — not positions.
To change the list, loop over indices or use list comprehension.
Example:
arr = [x * 2 for x in arr]Book: Probability and Statistics using Python
Summary
| Code | Modifies list? |
|---|---|
| for i in arr: i *= 2 | ❌ No |
| for i in range(len(arr)) | ✅ Yes |
| arr = [x*2 for x in arr] | ✅ Yes |


.png)

.png)





