Why does this
import numpy as np
a = np.array([[1,2,3],[4,5,6]])
a_old = a[0]
a[0] = a[0] np.array([1,1,1])
print(a[0] - a_old)
give
[0 0 0]
and not
[1 1 1]
? But on the other hand
b = 2
b_old = b
b = b 1
print(b - b_old)
gives indeed
1
as I would expect. I suppose there is a difference between assigning something to np.array elements, and assigning something to a variable. But I don't quite see through it. Thanks for help!
CodePudding user response:
This can be tricky in numpy! It's because that when you do a_old = a[0], you are creating a view of the data in a, not a copy of the data. To quote the numpy indexing documentation:
It must be noted that the returned array is a view, i.e., it is not a copy of the original, but points to the same values in memory as does the original array.
So when you add to the original array: a[0] = a[0] np.array([1,1,1]), the "value" of a_old changes as well since a_old points to the same location in memory. If you want to create a copy, you can simply edit your code:
a_old = a[0].copy()
In your floating point example, b_old = b copies the value of b to a new point in memory, so b and b_old can be changed without affecting one another.
CodePudding user response:
This happens because in Python, as well as other programming languages, lists are Reference type. So, the value stored in a[0], isn't the list but it's a memory address where the list is stored.
So, the instruction a_old = a[0], copy the address of a[0] in a_old, and both the variables will reference the same list.
Instead, doing b_old = b, you're copying the value 2 directly.
To notice this, try running print(a_old is a[0]), you should see True.
Now, to solve your problem, you can run a_old = a[0].copy().
After this, print(a_old is a[0]) will output False, because the reference of the two variables are different.
