[Tutor] Manipulate list in place or append to a new list
spir
denis.spir at free.fr
Sun Nov 2 17:41:56 CET 2008
Sander Sweers a écrit :
> On Sun, Nov 2, 2008 at 13:32, Kent Johnson <kent37 at tds.net> wrote:
>> Use a list comprehension:
>> somelist = [ x+1 for x in somelist ]
>
> Got it.
>
>> 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]
or e.g.
lines = [line.lower() for line in lines]
Both "pre-processing" actions that will make further processing more
straitforward. Note that you can chain actions:
lines = [line.strip().lower() for line in lines]
Denis
More information about the Tutor
mailing list