简体   繁体   中英

Changing variable values in for loop?

I'm confused about how variables modified in part of a for loop behave outside the loop. Encountered this problem when doing a more complicated analysis but realised it's a basic for loop issue, easily shown with a toy example:

x, y, z = 1, 2, 3

for i in [x, y, z]:
    i += 10
    print(i)

# prints 11
# prints 12
# prints 13

print(x, y, z)
# prints 1 2 3

I would've expected the change to each iterated-over variable in the loop to stick outside of the loop, but evidently this isn't the case. I gather it's probably something about variable scope? Could someone explain how this works?

Actually it is not related to scopes.

Here you are iterating using the value i and increasing only i value, not any of x,y or z variable. So x,y and z remain unchnaged.

To change, use like this:

b = {'x': 1,'y': 2, ,'z': 3}
for m in b.keys():
  b[m] += 10

Actually you don't even need a for loop to showcase this what you call an issue but is actually not.

Take this simpler example:

x = 1
i = x
i += 10
print(x)
print(i)

Ofcourse x is not modified because it holds an immutable value of 1 .

Here are immutable types in Python:

  • all primitive types: int , float , bool
  • plus tuple and str

Immutability means no shared reference . So that when you have: x = 1 y = 1 doesn't mean that x and y are referring to the same exact value 1 but instead each of the two variables have their "duplicate" instance of the same value. So that changing x doesn't affect y at all.

The same way, when you have: x = 1 i = x this is going to create a "brand new value of 1 " and assign it to i , so that modifying i doesn't affect variable x at all.

But now, to get the behavior you want you can do something like:

x, y, z = 1, 2, 3
l = [x, y, z]
for i in range(len(l)):
    l[i] += 10
x, y, z = l

Or if you really really want to be a little bit quirky, you can do:

x, y, z = 1, 2, 3
for var in locals().keys():
    if var in ['x', 'y', 'z']:
        locals()[var] += 10

But keep in mind that it is a good design decision from the creators of the language to keep certain types immutable, and so you should work with it instead and completely avoid using locals() as above or something else unnatural.

The thing is that i variable is like a "temporary" variable in the for statement. So you are assigning i to a value of the array in each iteration. Look at the next example:

array = [1, 2, 3]

for i in array:
    i += 10 #here we are modifying the "temporary" variable
    
print(array) #prints 1 2 3

index = 0
for i in array:
    array[index] += 10 #here we are modifying the array
    index += 1
    
print(array) #prints 11 12 13

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM