✅ Actual Output
[10 20 30]Why didn’t the array change?
Even though we write:
i = i + 5๐ This DOES NOT modify the NumPy array.
What really happens:
| Step | Explanation |
|---|---|
| for i in x: | i receives a copy of each value, not the original element |
| i = i + 5 | Only changes the local variable i |
| x | The original NumPy array stays unchanged |
So this loop works like:
But x never updates, so output is still:
[10 20 30]✅ Correct Way to Modify the NumPy Array
✔ Method 1: Using Index
✅ Output:
[15 25 35]✔ Method 2: Best & Fastest Way (Vectorized)
✅ Output:
[15 25 35]Key Concept (IMPORTANT for Interviews)
Loop variable in NumPy gives a copy, not a reference.
To change NumPy arrays, use indexing or vectorized operations.
Network Engineering with Python: Create Robust, Scalable & Real-World Applications


0 Comments:
Post a Comment