[Tutor] Variables don't change when altered within a loop?

Alan Gauld alan.gauld at freenet.co.uk
Fri Jun 30 13:54:46 CEST 2006


> Hi, I just started picking up python yesterday, and have already come
> across something that has me stumped.  I want some code that does
> this:
> 
> a = foo(a)
> b = foo(b)
> c = foo(c)
> 
> So I try to do this with a for loop, like so:
> 
> for i in [a, b, c]:
>   i = foo(i)
>   print i     # make sure that it worked correctly
> 
> So far, so good.  The problem is that outside the loop, the values
> aren't changed.  For example,

You need to understand the difference between names 
and variables and values. A variable in Python is a reference 
to a value (or more correctly an object which has a value)

for i in [a,b,c]

makes a new variable(name) i which takes on the *values* 
of a,b,c in turn with each iteration of the loop.

i does not take on the name a,b or c, it takes on the value.
Thus in the first iteration the variable i will take on the 
value referenced by a, in the second iteration the value 
referenced by b and in the third iteration the value 
referenced by c. The original variables still refer 
to their original values.

i = foo(a)

now i will be rebound to the value returned by the function 
foo() when passed the value of a as an argument. The value 
refered to by a has not been changed in any way.

print i

prints the new value associated with i. It changes nothing.

in the second iteration the same happens but with i 
taking on the initial value of b.

Lets look at a more concrete example:

def foo(x): return x + 10
a,b,c = 1,2,3

code                      iter 1         iter 2       iter 3
----------------------------------------------------------------
for i in [a,b,c]:         i = 1          i = 2         i = 3   
   i = foo(i)             i = 11         i = 12        i = 13

Note that a,b,c are not changed anywhere in this loop.
They retain the original values of 1,2,3.
If you wanted to change them you would need to explicitly 
set their values

> What is going on?  
> Why aren't the values of my variables changing when
> I change them inside a loop like this?

You are not changing the variables you are changing i 
which is an entirely different variable!

The normal way to do what I think you want is to 
put the variables in a list or dictionary, then 
you can loop over that and change the values. 
Like so:

vars = {'a':1, 'b':2,'c':3}
def foo(x): return x+10
for key,value in vars.items():
    vars[key] = foo(value)

print vars

HTH,

Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20060630/ceba6517/attachment.htm 


More information about the Tutor mailing list