[Tutor] Manipulate list in place or append to a new list
Kent Johnson
kent37 at tds.net
Sun Nov 2 19:55:02 CET 2008
On Sun, Nov 2, 2008 at 12:41 PM, spir <denis.spir at free.fr> wrote:
> Sander Sweers a écrit :
>>> Note that this creates a new list, replacing the one that was in
>>> somelist. If you need to actually modify somelist in place (rare) then
>>> use somelist[:] = [ x+1 for x in somelist ]
>>>
>>> which creates a new list, then replaces the *contents* of somelist
>>> with the contents of the new list.
>>
>> In what (rare) situation would you use this?
>
> [post sent again -- seems not to have reached the list -- ??]
> When you need to cleanup or normalize the objects held in a list. For
> instance,
> in text processing:
> lines = text.splitlines()
> lines = [line.strip() for line in lines]
> <etc>
These are good examples of list comp but note that Sander was
specifically asking when you might want to replace a list in place
using the somelist[:] syntax.
Kent
More information about the Tutor
mailing list