I have a global variable, things (a list), used within two functions. In one function, save_thing, I want to save the original variable as a value to a key in a dictionary that when printed, shows: {'First thing': ['a', 'b']}. I can successfully do this.
In another function, change_thing, I want to use a copy of things (a local variable) only within change_thing. Then I want to remove the first list item, 'a', from the local variable. But I can't figure out how to make a copy of the global variable used locally. Instead, the global variable is changed, and the dictionary used in the first function, save_thing, is changed. And I don't want that.
I thought that passing the global variable as an argument/parameter in the function would make it be used locally, but that is wrong. I understand that in my code, the global variable (things) is set as the value in the dictionary and when the change_thing function alters the global variable, the dictionary is also altered.
Ultimately, I want to understand how to pass global variables into functions and use them locally without changing the global. I haven't been able to find examples of this elsewhere.
things = ['a', 'b']
dictionary = {}
def save_thing(parameter):
dictionary['First thing'] = parameter
print('Dictionary BEFORE change_thing is run', dictionary)
def change_thing(parameter):
parameter.remove('a')
save_thing(things)
change_thing(things)
print('Dictionary AFTER change_thing is run', dictionary)
When run, the above code prints:
Dictionary BEFORE change_thing is run {'First thing': ['a', 'b']} Dictionary AFTER change_thing is run {'First thing': ['b']}
I want the dictionary to always be {'First thing': ['a', 'b']} and not impacted by the change_thing function.
Any feedback is appreciated. Thanks.