[Tutor] Changing lists in place
Alan Gauld
alan.gauld at freenet.co.uk
Tue Apr 18 00:32:10 CEST 2006
> I have a list that I want to change in a for loop.
Thats nearly always a bad thing to do.
Its like the old cartoon of the guy vcutting off the
branch of the tree while sitting on it. Python can
get very confused.
Either make a copy and change the copy or use
a while loop and an index.
However, as others have pointed out:
mylist = [ 'One ', ' two', ' three ' ]
print mylist
for element in mylist:
element is a copy of the value in mylist, it is not a
reference to mylist[n]
element = element.strip()
print "<>" + element + "<>"
so changes to element are not changes to the
list content.
If you want to change the list content use a while loop:
index = 0
while index < len(mylist):
mylist[index] = '<> + mylist[index].strip() + '<>'
index += 1
Or a list comprehension:
mylist = ['<>' + n.strip() + '<>' for n in mylist]
But notice that the comprehension builds a new list it
does not actually change mylist directly in the way the
while loop does.
Alan G
Author of the learn to program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld
More information about the Tutor
mailing list