0

I am relatively new to Python and love it. If I have a problem, usually I manage to find my own solutions, or relative topics that can help me understand where I messed up. But this one I can't seem to wrap my head around it.

So the issue I'm facing right now is that I give a class1.list to another class2.function, where I do some stuff there with that list. My issue is that my class1.list changes in that function and I don't understand why:

class ClassA():
    def function_a(self, test):
        test[0][0] = '?'
        test[0][1] = '?'
        return test

class ClassB():
    class_b_list = [[1,2],[3,4]]
    def function_b(self,value):
        value[1][0] = 350
        value[1][1] = 250
        return value



my_class_a = ClassA()
my_class_b = ClassB()

print(my_class_b.class_b_list)

my_class_a.function_a(my_class_b.class_b_list)
my_class_b.function_b(my_class_b.class_b_list)

print(my_class_b.class_b_list)

So my first print will give me the actual value of the list: [[1,2][3,4]]

But after I give it as an attribute, my list changes to: [['?','?'][350,250]]

What am I missing? I don't want my_class_b.class_b_list to change.

Rahzyel
  • 3
  • 1

1 Answers1

2

Don't try to mutate the argument. Copy it first, then change and return.

from copy import deepcopy

class ClassA():
    def function_a(self, test):
        # use deep copy if you're using nested lists, or mutating object/dict in list
        test = deepcopy(test)
        # if not, slice copy is usually enough
        # test = test[:]

        test[0][0] = '?'
        test[0][1] = '?'
        return test

Also see: How to clone or copy a list?

abdusco
  • 9,700
  • 2
  • 27
  • 44
  • 1
    Slice will only shallow copy the list. This is a nested list, so they would have to use `copy.deepcopy` or something like that. – Håken Lid Jul 20 '19 at 10:51