3

I am trying to make a copy of a numpy array in python. I would then like to change some values of the new array, however somehow this also changes the original?

Why is the following code not correct?

import numpy as np

a = np.array([1,1])
print("Array a:",a)

b = a
b[0] = a[0]*2
print("Array b after manipulation:", b)

print("Array a, after manipulating array b", a)

The only way I can make it work is by list comprehensions.

import numpy as np

a = np.array([1,1])
print("Array a:",a)

b = [x for x in a]
b[0] = a[0]*2
print("Array b after manipulation:", b)

print("Array a, after manipulating array b", a)
Mathias
  • 33
  • 3

1 Answers1

3

Assignment statements in Python do not copy objects, you need to use copy():

b = a.copy()
jlesuffleur
  • 1,113
  • 1
  • 7
  • 19
  • Thank you for the (quick!) answer. Do you have an explanation to why? I believe the first solution is very intuitive. Is it because I use the numpy array instead of a list? – Mathias Mar 11 '21 at 15:59
  • It only works at first level, it doesn't work if you copy an array of arrays. – lolesque Dec 05 '22 at 10:47