List unchanged in function--why?

Alex Martelli aleax at aleax.it
Mon Feb 18 11:49:59 EST 2002


Chris wrote:

> This must have something to do with references etc, but I'm not sure
> what's going on.
> 
> def changeList(theList):
>   theList = ['a']

You're re-binding the local name 'theList' so that it now refers
to a different object to whatever it previously referred to.

Rebinding a name never affects whatever object the name was
previously bound to.

Maybe what you want to do is instead, as the body of changeList:

    theList[:] = ['a']

this rebinds the *whole-list slice*, i.e. the CONTENTS of the
object currently bound to local name 'theList', rather than
the name itself.  Apparently you do want to rebind the contents
of the object, rather than the name, right?


Alex




More information about the Python-list mailing list