On Sun, Nov 2, 2008 at 9:13 AM, Sander Sweers <[EMAIL PROTECTED]> wrote: > On Sun, Nov 2, 2008 at 13:32, Kent Johnson <[EMAIL PROTECTED]> 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 _______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
