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?

2
  • Possible duplicate of How to clone or copy a list? Commented Jun 10, 2018 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]. Commented Jun 10, 2018 at 20:49

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

This does not work. Slicing creates a view in numpy, and now x and y share the same underlying buffer. You have to use .copy
@juanpa.arrivillaga i've updated the answer to reflect that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.