assignment in a for loop

MackS mackstevenson at hotmail.com
Wed May 17 00:46:26 EDT 2006


Sorry, my previous post probably was not very good at explaining _why_
I want to do this.

Suppose I want to do modify all arguments which are passed to a
function. Do I need to use a list comprehension such as

def f(arg1,arg2,arg3):

     arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)]
     ...

This would be awful when, eg, one adds an argument to the function
definition. It would require edition of the code at two different
locations.

Thanks

Mack

MackS wrote:
> Hello everyone
>
> Consider the following
>
> >>> l = [1,2]
> >>> for i in l:
> ...     i = i + 1
> ...
> >>> l
> [1, 2]
>
> I understand (I think!) that this is due to the fact that in Python
> what looks like "assignment" really is binding a name to an object. The
> result is that inside the loop I am creating an object with value (i+1)
> and then "pointing" the name i at it. Therefore, the object to which i
> previously pointed (an element of list l) remains unchanged.
>
> Two brief questions:
>
> 1) Is what I wrote above (minimally) correct?
>
> 2) Independently of the answer to 1, is there a way for me to assign to
> elements of a list inside a loop and without resorting to C-style
> ugliness of
>
> for i in range(len(l))
>      l[i] = l[i] + 1
>
> ?
>
> (Note: not using a list comprehension.)
> 
> Thanks in advance
> 
> Mack




More information about the Python-list mailing list