1

My code is below:

import numpy as np

class xx():
   def __init__(self, x):
      self.x = x
   def main(self):
      for i in [0,1,2,3]:
         y = self.x
         y[0, i] = 0
         print(y)
z = np.array([[0.5,0.6,0.7,0.8],[1,2,3,4],[6,4,3,1]])        
xx(z).main()

My original code is far more complicated than this, so I decided to create a similar example on the issue.

I meant to only change y in the for loop, and reassign y with self.x. but it seemed that self.x was changed in the for loop too. How can I avoid self.x getting modified each time as y changes?

2
  • 2
    Could not recreate, I get your desired output as expected. Strings are immutable, and you don't explictly update self.x, so each assignment y = self.x gets the value 'David'. Commented Jun 1, 2021 at 20:16
  • well it seems your current code currently gives me the desired output. you may need to clarigy more Commented Jun 1, 2021 at 20:24

1 Answer 1

1

I would recommend using copy.deepcopy()

import copy

class xx():
   def __init__(self, x):
      self.x = x
   def main(self):
      for i in [0,1,2]:
         y = copy.deepcopy(self.x)
         y[0, i] = 0
         print(y)
z = np.array([[1,1,1],[2,2,2]])
xx(z).main()

>>>[[0 1 1]
    [2 2 2]]

>>>[[1 0 1]
    [2 2 2]]

>>>[[1 1 0]
    [2 2 2]]
Sign up to request clarification or add additional context in comments.

2 Comments

In my original code, it's numpy array. So python does not distinguish two objects such as dataframe numpy when reassigning? The variables are pointing to the same object using '='?
I'm not exactly sure what you mean, but notice that when you wrote the line y = self.x and then y[0, i] = 0 those two lines are equivalent to self.x[0, i] = 0 , since the y variable is just a pointer to self.x, when you use copy.deepcopy() you create a new object in the memory and can modify it without overwriting self.x

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.