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

anton muhin antonmuhin at rambler.ru
Tue Feb 10 06:11:44 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)
You're wrong: in Python you pass references to objects.
> 
> Example 1.
> def ChangeList(ListToChange):
> 	ListToChange[1] = "Line B"
Now you change the second element of list that is referenced by 
ListToChange identfier
> 
> 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"]
Attention: (4) rebinds variable ListToChange to new list ["Line X","Line 
Y","Line Z"]. However, statemets (2) and (3) modified 2nd and 3rd 
elements of passed list and you don't see a bug.

> 
> Result is the same (as it suppose to be..)
> ["Line 1","Line 2","Line 3"]
> ["Line 1","Line B","Line C"]
> 
> 
> 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"
And here comes a trap: in (3) you rebind ListToChange and (4) modifies 
new list.

You can use id function to track objects:

(1) def ChangeList(ListToChange):
(2)	ListToChange[1] = "Line B"; print id(ListToChange)
(3)	ListToChange[2] = "Line C"; print id(ListToChange)
(4)	ListToChange = ["Line X","Line Y","Line Z"]; print id(ListToChange)


(1) def ChangeList(ListToChange):
(2)	ListToChange[1] = "Line B"; print id(ListToChange)
(3)	ListToChange = ["Line X","Line Y","Line Z"]; print id(ListToChange)
(4)	ListToChange[2] = "Line C"; print id(ListToChange)

And another note: you may read more on mutable and immutable types as 
well, because it's usual source of confusion for Python newcomers.

And the last note: IMHO, modification of passed parameters isn't really 
Pythonic (again, IMHO) --- it's common thing in C++ and alike languages 
where function can return only single value, but in Python you can 
return multiply values and shouldn't modify passed parameters. Of 
course, there might be situations where modification is really must, but 
I'd try to avoid them.

regards,
anton.



More information about the Python-list mailing list