1

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!

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Python
  • 359
  • 2
  • 16
  • 1
    You could have just written `z = -x`, that's the whole point of NumPy arrays. – mkrieger1 May 01 '21 at 08:51
  • @mkrieger1 the link you sent is related to lists. But what if I do not want to do casting from array to list and back? You are right about 'z = -x' ! But in general, I want to change not all elements in 'z', but few of them. So how could I solve this? – Python May 01 '21 at 08:56
  • The explanation is valid for both lists and NumPy arrays. You need to make a copy of the array. – mkrieger1 May 01 '21 at 08:57
  • @mkrieger1 you are right! That answers my question – Python May 01 '21 at 08:58

1 Answers1

-1

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]
arshovon
  • 13,270
  • 9
  • 51
  • 69