Change global variables from inside class method

When I try to execute the code below, the first_list gets modified while no changes occur to the second one. Is there a way to replace an outside list with a brand new list, or calling list methods is the only thing I'm allowed to do from inside class methods? I tried adding global keyword before the assignment operation, but it produces a syntax error.

first_list = []
second_list = []


class MyClass:

    def change_values(self):
        first_list.append('cat')
        second_list = ['cat']

 test = MyClass()
 test.change_values()
 print(first_list)
 print(second_list)

Answers


First: It's almost NEVER a good idea to have global variables with mutable state. You should use module level variables just as constants or singletons. If you want to change a value of a variable you should pass it as a parameter to a function and then return a new value from a function.

Said that the answer to your question would be either:

first_list = []
second_list = []


class MyClass:
    def change_values(self):
        first_list.append('cat')
        second_list[:] = ['cat']

test = MyClass()
test.change_values()
print(first_list)
print(second_list)

or:

first_list = []
second_list = []


class MyClass:
    def change_values(self):
        first_list.append('cat')
        global second_list
        second_list = ['cat']

test = MyClass()
test.change_values()
print(first_list)
print(second_list)

Need Your Help

How to initialize a 3d array in C - Array of arrays of pointers

c arrays pointers malloc

I am programming a game which generates the next possible moves. I need to generate the next moves in order to perform the search. However I have no idea about how to do it in C.

Spring and forms with select

java spring data-binding

I am using Spring to populate a item in a form, using object passing between controller and views: