[Tutor] Changing lists in place
Paul D. Eden
paul at benchline.org
Mon Apr 17 21:04:57 CEST 2006
Very true.
Paul
Kent Johnson wrote:
> 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
>
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
More information about the Tutor
mailing list