List unchanged in function--why?

Michael Chermside mcherm at
Mon Feb 18 17:54:41 CET 2002

> This must have something to do with references etc, but I'm not sure
> what's going on.

Yes... It has to do with references. Let me explain.

> def changeList(theList):
>   theList = ['a']
> aList = ['x', 'y']
> print aList
> changeList(aList)
> print aList
> Running the above results in
> ['x', 'y']
> ['x', 'y']
> Can someone explain?  I was expecting the second line printed to be
> ['a']

Sure. The argument theList is passed "by reference" (the ONLY way that 
args are passed in Python), so you can mutate the object if you like. 
But you didn't... your line "theList = ['a']" CHANGES what the local 
variable 'theList' refers to, instead of modifying the object it now 
refers to.

This should achieve what you wanted:

def changeList(theList):
   theList[:] = ['a']

It's not a very useful idiom... if you wanted to replace the entire 
contents of the list the BEST way to do it is like this:

def makeNewList():
    return ['a']
aList = makeNewList()

But of course you were really only experimenting. Your real goal is 
probably not to replace the entire list but modify the list... append 
new items onto it perhaps. And those kinds of operations work really 
well the way you started out:

def addToList(theList, newItem):

Have fun!

-- Michael Chermside

More information about the Python-list mailing list