[Tutor] Changing lists in place
Kent Johnson
kent37 at tds.net
Mon Apr 17 21:01:59 CEST 2006
Paul D. Eden wrote:
> Lists are mutable, you are right.
>
> But the code you gave does not change the list. It changes the variable
> element which is separate from the list myList.
>
> If you want to change the list try something like this:
>
> mylist = [ 'One ', ' two', ' three ' ]
> print mylist
> newlist = []
> for element in mylist:
> element = element.strip()
> newlist.append(element)
> print "<>" + element + "<>"
> print newlist
>
> OR
>
> mylist = [ 'One ', ' two', ' three ' ]
> print mylist
> mylist = [element.strip() for element in mylist]
> for element in mylist:
> print "<>" + element + "<>"
> print mylist
Neither of these changes the original list either. They both create new
lists with the desired contents. The second example binds the new list
to the old name, but it is still a new list. In many cases this is fine,
but the distinction is important. For example if you are writing a
function that modifies a list passed to it, these solutions won't work.
Bob's solution using enumerate() is the simplest way to modify a list in
place.
Kent
More information about the Tutor
mailing list