for v in l:

G

Gert Cuykens

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=v+x

something like

for v in l:
l[v]=l[v]+x
 
D

Dennis Lee Bieber

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=v+x

Many of them... Starting with the most rudimentary:

for i in xrange(len(l)):
l = l + x #or... l += x

Just don't delete or extend the list while inside the loop
--
Wulfraed Dennis Lee Bieber KD6MOG
(e-mail address removed) (e-mail address removed)
HTTP://wlfraed.home.netcom.com/
(Bestiaria Support Staff: (e-mail address removed))
HTTP://www.bestiaria.com/
 
P

Peter Otten

Gert said:
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=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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,681
Members
48,796
Latest member
Greg L.

Latest Threads

Top