0

In Python 3.11, I would like to understand why when a value of my dictionary references a variable, this one is modified in a while loop but not as a value of my dictionary. Example :

my_variable = 0 
my_dict = {'offset' : my_variable}
i = 0

while i < 3:
    my_variable += 50
    print(f'my_variable = {my_variable}')
    print(f'my_dict['offset'] = {my_dict['offset']}')
    i += 1



>>> my_variable = 50
    my_dict['offset'] = 0
    my_variable = 100
    my_dict['offset'] = 0
    my_variable = 150
    my_dict['offset'] = 0

I found my error, I have to use : my_dict['offset'] += 50 instead of my_variable += 50

My question is "why does this work that way". Why when I modify the value of my variable, it does not apply to objects referencing it. I found this question on stackoverflow Python, reference to variable in a dictionary but it seems that there is a lot of debate in comments and the answer is not extremely clear to me. Thanks to anyone who will take the time to reply or attach a url to a useful resource.

La Gruge
  • 1
  • 1

0 Answers0