Final Output
[1 2 3]๐ The array does NOT change.
Why the Array Doesn't Change
๐น 1. for i in a: gives you a copy of each element
i is just a temporary variable
-
It does NOT modify the original array a
So this line:
i = i * 2✔️ Only changes i
❌ Does NOT change a
๐น 2. What Actually Happens Internally
Iteration steps:
| Loop Step | i Value | i * 2 | a (unchanged) |
|---|---|---|---|
| 1 | 1 | 2 | [1 2 3] |
| 2 | 2 | 4 | [1 2 3] |
| 3 | 3 | 6 | [1 2 3] |
You never assign the new values back into a.
✅ Correct Way to Modify the NumPy Array
✅ Method 1: Using Index
✅ Output:
[2 4 6]✅ Method 2: Vectorized NumPy Way (Best & Fastest)
✅ Output:
[2 4 6]Key Concept (Exam + Interview Favorite)
❗ Looping directly over a NumPy array does NOT change the original array unless you assign back using the index.


0 Comments:
Post a Comment