I want to change a variable's value by reaching it from a list, not the list item's value. Is there a way to do that?
variable1 = 5
variable2 = 10
my_list = [variable1, variable2]
my_list[0] = 8
print(f"list: {my_list}\n"
f"variable1: {variable1}\n"
f"variable2: {variable2}")
Output:
list: [8, 10]
variable1: 5
variable2: 10
Expected output:
list: [8, 10]
variable1: 8
variable2: 10
CodePudding user response:
Store your variable
s as a dict, and store the dict keys in your list.
variables = {
1: 5,
2: 10,
}
my_list = [1, 2]
variables[my_list[0]] = 8
print(f"my_list: {[variables[i] for i in my_list]}\n"
f"variable1: {variables[1]}\n"
f"variable2: {variables[2]}")
prints:
my_list: [8, 10]
variable1: 8
variable2: 10
This works because the list now contains references (which you can dereference by doing a lookup in variables
). Variables in Python always refer to values, and can't be used as references in and of themselves (but the values can themselves be references to other things).
Another option is to make your list values mutable, so that you can reach in and mutate the actual value rather than reassigning the index of the list to a new value. Note that int
s are immutable, so you can never modify an int value directly, only reassign one of its references to a whole different value.
class MutableVar:
def __init__(self, val):
self.val = val
def __repr__(self):
return repr(self.val)
variable1 = MutableVar(5)
variable2 = MutableVar(10)
my_list = [variable1, variable2]
my_list[0].val = 8
print(f"my_list: {my_list}\n"
f"variable1: {variable1}\n"
f"variable2: {variable2}")
Again, the key thing here is that your list contains references to the actual int values; in this case the reference is the val
attribute of a MutableVar
object, rather than a key for a dict.