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

Bob Gailer bgailer at alum.rpi.edu
Fri Jun 30 02:27:14 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
>   
Typically in Python we'd store the values in a list (or dictionary), 
then apply the function to each element of the list (or dictionary). 
Python's list comprehension does this nicely:

abc = [a, b, c] # from here on we forget the individual names a,b,c and 
work on list elements instead:
abc = [foo(x) for x in abc] # this applies foo to each element of abc, 
constructs a new list and assigns it to abc.

Alternatively we could write:
for idx, val in enumerate(abc):
    abc[idx] = foo(val)
> 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?
>
> -- Evan
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>   


-- 
Bob Gailer
510-978-4454



More information about the Tutor mailing list