0

I am having an issue when I assign an array of data to a new variable and try to change elements within the new variable. For instance, if I have the array y = [1,2,3], I set the value of a new array y1 to be: y1 = y. Then, I want to change the first element of y1 to be 9 without changing y. However, when I execute the command y1[0] = 9, it changes the first element of y1 and y. How can I change y1 without changing y?

Here is an example of my code,

import numpy as np
y = np.array([1,2,3])
y1 = y
y1[0] = 9
print(y1)
print(y)

I expected the output to be:

array([9,2,3])
array([1,2,3])

However, the code returns the following

array([9,2,3])
array([9,2,3])
AC1721
  • 3
  • 1
  • 1
    With a simple stackoverflow search: https://stackoverflow.com/questions/19341365/setting-two-arrays-equal – gonidelis Aug 21 '19 at 15:56

1 Answers1

1

Use y.copy() to create a new copy of the array:

import numpy as np

y = np.array([1,2,3])
y1 = y.copy()
y1[0] = 9

print(y1)
print(y)

Output:

[9 2 3]
[1 2 3]
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55