[Tutor] Variables don't change when altered within a loop?
Bob Gailer
bgailer at alum.rpi.edu
Fri Jun 30 02:22:24 CEST 2006
Evan Klitzke wrote:
> 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,
>
> print [a, b, c] # outside the loop; the values never actually changed!
>
> What is going on? Why aren't the values of my variables changing when
> I change them inside a loop like this?
>
The program is not changing a or b or c in the loop. The for statement
assigns a to i. The next statement assigns a new value to i. a is not
affected. Change print i to print i, a, b, c # and note that a, b, c are
unchanged.
--
Bob Gailer
510-978-4454
More information about the Tutor
mailing list