Can somebody explain why x
changes in the following code?
x = np.arange(0, 5, 1)
z = x
for i in range(len(x)):
z[i] = -z[i]
print(z)
print(x)
out:
[ 0 -1 -2 -3 -4]
[ 0 -1 -2 -3 -4]
How can I prevent x
from changing?
Thanks a lot!
Can somebody explain why x
changes in the following code?
x = np.arange(0, 5, 1)
z = x
for i in range(len(x)):
z[i] = -z[i]
print(z)
print(x)
out:
[ 0 -1 -2 -3 -4]
[ 0 -1 -2 -3 -4]
How can I prevent x
from changing?
Thanks a lot!
Assigning a list to a variable, copies it by reference. So changing in one list will affect the other.
If you want to copy the values only, you can use list.copy()
method.
import numpy as np
x = np.arange(0, 5, 1)
z = x.copy()
for i in range(len(x)):
z[i] = -z[i]
print(z)
print(x)
Output:
[ 0 -1 -2 -3 -4]
[0 1 2 3 4]