0

Can't think of a better way to phrase this: but basically I am trying to create a copy of a list that I don't want to change, so that when elements are added in the future I can compare the two and see what's different.

class model(object):
     def __init__(self):
          self.scale = ["some_stuff","other stuff"]
          self.scale_old = self.scale

And when I run this code to create an instance and add an element to the list--it seems to rerun the init method and recreate the "scale_old" variable. I'm confused because it was my understanding the constructor only ran once.

 current_model = model()
 print(current_model.scale_old)
 current_model.scale.append("yoyoyo")
 print(current_model.scale_old)

Output: ['some stuff', 'other stuff'] ['some stuff', 'other stuff', 'yoyoyo']

I've tried Googling several different things and not sure how else to phrase this. Would appreciate some direction. Thanks!

S420L
  • 117
  • 10

1 Answers1

3

You'll need to explicitly copy the list rather than just setting the variables equal to each other.

In python, variables are just references to an object. Two variables can be referenced to the same object. This is what you did with self.scale_old = self.scale that is simply two variables referenced to the same object. When you change one, both change.

How to clone or copy a list?

class model(object):
     def __init__(self):
          self.scale = ["some_stuff","other stuff"]
          self.scale_old = self.scale.copy()
user1558604
  • 947
  • 6
  • 20