0

Goal: I want to create a list, make a copy of it, and manipulate the copy while not affecting the original.

I created a toy example to show the problem. When I copy the listand append the copy, somehow this traces back to the original. How can I keep this from affecting the original?

class testing:

    def __init__(self):
        self.array1 = [1, 2, 3, 4, 5]
        self.array2 = self.array1

    def display1(self):
        print(self.array1)

    def display2(self):
        ary = self.array2
        ary.append(6)
        print(ary)

if __name__ == "__main__":
    test = testing()
    test.display1()
    test.display2()
    test.display1()

The result is:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5, 6]

The third result shows that the first list has the appended '6' that was only added to the copy list

Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36

1 Answers1

2

You're very close.

Just add .copy() when you define ary.

So, in the first line of display2, use this instead ary = self.array2.copy()

class testing:

    def __init__(self):
        self.array1 = [1, 2, 3, 4, 5]
        self.array2 = self.array1

    def display1(self):
        print(self.array1)

    def display2(self):
        ary = self.array2.copy()
        ary.append(6)
        print(ary)

if __name__ == "__main__":
    test = testing()
    test.display1()
    test.display2()
    test.display1()

now returns

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 6]
[1, 2, 3, 4, 5]

As chepner notes, these are lists, not arrays. For Numpy arrays, you would want to use ary = np.copy(self.array2) to achieve the same result.

treetopper
  • 46
  • 4