1

I need to do calculations on an intial 3x3 array (say 'x') which I would need again later for further calculations. So, I have another variable ('y') to make a copy of 'x' (y = x), do calculations on 'y' and then use x for later purposes. But somehow address of 'y' changes to 'x' even if I assign it initially other than 'x'

import numpy as np

x = np.random.rand(3,3)
y = np.random.rand(3,3)

print 'y',id(y)

y = x
y[1][1] = -y[1][1]

print x[1][1] + y[1][1]  #This needs to be 0.
print 'x',id(x)
print 'y',id(y)

In the above code, I need line 9 ('x[1][1] + y[1][1]'), to print 0, but what is giving is 2 times -x[1][1]. What is the reasoning behind this problem and if you could suggest some method to avoid this?

luffy
  • 105
  • 8
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – Thierry Lathuille Jun 10 '18 at 18:32
  • When indexing a numpy array, get in the habit of using `y[1, 1]` instead of `y[1][1]`. Here they do the same thing, but `y[:][1]` is not the same as `y[:,1]`. – hpaulj Jun 10 '18 at 20:49

1 Answers1

1

Because y=x copies just the refrence, and does not create another copy of the array

You should replace that line with

y = x[:]

Otherwise changing x also changes y and vise versa.

However, this method is good only for a regular list and not numpy arrays. That is possible like this (also more explicit and readable):

y = np.copy(x)

If you want to check it yourself, you can print id(y) and print id(x) after that assignment, and see that in your case they are the same, while in a true copy they are different

Ofer Sadan
  • 11,391
  • 5
  • 38
  • 62