By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,965 Members | 1,631 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,965 IT Pros & Developers. It's quick & easy.

for v in l:

P: n/a
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
Jan 16 '07 #1
Share this Question
Share on Google+
3 Replies


P: n/a
Try:
l = [i+x for i in l]
OR
l = map(lambda i: i+x, l)

-N

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
Jan 16 '07 #2

P: n/a
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
Jan 16 '07 #3

P: n/a
ok thx this was just what i was looking for

http://docs.python.org/tut/node7.htm...00000000000000
Jan 16 '07 #4

This discussion thread is closed

Replies have been disabled for this discussion.