for v in l:

Peter Otten __peter__ at web.de
Tue Jan 16 03:42:43 EST 2007


Gert Cuykens wrote:

> is there a other way then this to loop trough a list and change the values
> 
>         i=-1
>         for v in l:
>                 i=i+1
>                 l[i]=v+x
> 
> something like
> 
>         for v in l:
>                 l[v]=l[v]+x

Be generous, create a new list:

items = [value + delta for value in items]

That will require some extra peak memory, but is faster.
Also, code relying on lists not being changed in place tends to be more
robust (and better looking) than code relying on lists being changed in
place :-)

If you cannot rebind the list variable, use slices:

items[:] = [value + delta for value in items]

If the list is huge and you have to economize memory, use enumerate():

for index, value in enumerate(items):
   items[index] = value + delta

Peter



More information about the Python-list mailing list