[Tutor] Manipulate list in place or append to a new list

Kent Johnson kent37 at tds.net
Sun Nov 2 15:34:23 CET 2008


On Sun, Nov 2, 2008 at 9:13 AM, Sander Sweers <sander.sweers at gmail.com> wrote:
> On Sun, Nov 2, 2008 at 13:32, Kent Johnson <kent37 at tds.net> wrote:

>> 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?

For example if you have a function that adds one to each element of a
list passed to it.

def brokenAdder(somelist):
  somelist =  [ x+1 for x in somelist ]

This just modifies the local name, the caller will not see any change.

def adder(somelist):
  somelist[:] =  [ x+1 for x in somelist ]

In this case the caller will see a changed list.

Basically any time you have two names referencing (aliasing) the same
list and you want changes to the list to be seen for all the aliases.
Function parameters are a simple example of aliasing.

Kent


More information about the Tutor mailing list