Simple newbie question about parameters handling in functions (or am I dump or what?)

Peter Otten __peter__ at web.de
Tue Feb 10 06:06:24 EST 2004


Niki Iv wrote:

> I am totaly new to Python, although I have quite strong developer
> background. Indeed I am evaluating Python to integrate it (Jython) in
> my Java apps...
> Well this is my first Python day. I am tampering with functions. I
> read that parameters are passed by-value rather than by-reference. So
> function can change wathever parameters reffers to. My troube (well my
> presonal not understanding comes from this)
> 
> Example 1.
> def ChangeList(ListToChange):
> ListToChange[1] = "Line B"
> 
> MyList = ["Line 1","Line 2","Line 3"]
> print MyList
> ChangleList(MyList)
> print MyList
> 
> Result is quite understandable (as in Pythin Bible is..)
> ["Line 1","Line 2","Line 3"]
> ["Line 1","Line B","Line 3"]
> 
> So now function ChangeList.. is
> (1) def ChangeList(ListToChange):
> (2)   ListToChange[1] = "Line B"
> (3)   ListToChange[2] = "Line C"
> (4)   ListToChange = ["Line X","Line Y","Line Z"]
> 
> Result is the same (as it suppose to be..)
> ["Line 1","Line 2","Line 3"]
> ["Line 1","Line B","Line C"]
 
Strange. Most newbies would expect ["Line X","Line Y","Line Z"] (abreviated
[XYZ] hereafter). If you want to change the original list to [XYZ] at once,
do

ListToChange[:] = ["Line X", "Line Y", "Line Z"]

instead.
 
> But now... I am swaping line
> (1)def ChangeList(ListToChange):
> (2)   ListToChange[1] = "Line B"
> (3)   ListToChange = ["Line X","Line Y","Line Z"]
> (4)   ListToChange[2] = "Line C"
 
In (3) you are rebinding the local identifier ListToChange to the new [XYZ]
list. Every change that follows affects this list, so at the end of the
function you throw away the [XYC] list. You can easily verify that by
inserting a print statement into the function. By the way, wouldn't that be
the same in Java? If you think of Python as an "all pointers" language, you
should get it mostly right.

> I have only swapped line 3 and 4.

(1) animal = Monkey()
(2) animal.eatBanana()
(3) animal = Bird()
(4) animal.layEgg()

Expect to see strange things happen if you change lines 3 and 4 :-)
ListToChange = [...] has the same structure as my (3) - except that you
stuck to the same type while I switched to make it more obvious.

Peter




More information about the Python-list mailing list