Reputation: 31
For Example:
Variable = 1
List = [0, Variable, 2, 3]
Variable = 5
print(List)
output is [0,1,2,3]. Is there a way to get [0,5,2,3] other than redefining the list? Also, can it be done in reverse (i.e. List[1] = 5, making Variable == 5)?
Upvotes: 3
Views: 1525
Reputation: 29
Firstly, you need to understand why your code will not work the way it's supposed to. First of all you declared the variable Variable
and initialized it as 1. You then used it in a list. Now your list contains the values of 0, Variable, 2, 3 which is the same as the list containing the values of 0, 1, 2, 3. Now you updated the variable called Variable
and you changed it to 5. You see, you updated the variable but not the list... The list has no use of a variable, so it extracted the data it needed from that variable which was the number one... So it was as if you never even put a variable called Variable
, it was as if you just put the number one... So when you updated variable, the list was just looking at it like, "That package's not for me, I already got mine!". Now enough gibberish... down to the solution! First after creating the list, if you know you want to update that particular value, you store it in a variable:
Variable = 1
List = [0, Variable, 2, 3]
Variable = List[1]
Now the list sees that you are using this value, and updates along with it... So if you update it you are not updating the variable but are updating a value in the list:
Variable = 1
List = [0, Variable, 2, 3]
Variable = List[1]
Variable = 5
So if you tell it to print the list:
print(List)
Your result is "[0, 5, 2, 3]"! Hope this helped!
Upvotes: 1
Reputation: 77347
Not directly. The list isn't going to know about the reassignment and there isn't any way to intercept the reassignment and do some meta programming. (*Except wrong, see note). If Variable
is a container, you can update its contents and both would see. It could be a dict
or a list
for instance. But a class is a convenient way to do it. In this easy example, all users have to know to use variable.val
but you could also put the time into implementing all of the dunder methods to abstract that away.
class Variable:
def __init__(self, val):
self.val = val
variable = Variable(1)
my_list = [0, variable, 2, 3]
variable.val += 1
my_list[1].val += 1
print(variable.val)
*Note from the comments in the original question that assignment can be overridden, but its messy. This method is more clear to me, but if you like magic, then https://stackoverflow.com/a/52438651/642070
Upvotes: 4
Reputation: 11
Python variable hold the reference of values.
Variable = 1 List = [0, Variable, 2, 3]
In your list you pass the Variable reference not value itself.
List[1] = Variable
Upvotes: 0