[Tutor] passing by reference

Alan Gauld alan.gauld at btinternet.com
Sun Mar 13 10:25:22 CET 2011


"Vineeth Mohan" <vineethrakesh at gmail.com> wrote

> How are variables in python passed. By value or by referrence?

Neither, and trying to force a comparison to these traditional
styles will always lead to an exercise in frustration as you
find cases which don't quite fit..

Variables in Python are names that refer to objects.
Some objects are mutable others immutable.
Python functions take names as their parameters.
Those names refer to objects. Whether those objects
can be changed from inside the function depends upon
the mutability of the oject to which the name refers.

> example if we consider a simple function below wherein the value of 
> a does not get modified in the main function.
>
> def addition(a,b):
>     a = a+1
>     return a+b

In fact the value of a does get modified. What does
not get modified is the original object that a referred
to when the function was called. When you do

a = a+1

you make the name 'a' point to a completely new object
and that is what is returned.

> Is the following the only way to pass by reference? or is there any 
> other way
>
> def addition(x):
>     x.a = x.a+1
>     return x.a+x.b

You could pass a list too:

def addition(p):
     p[0] += 1
     return p[0]+p[1]

Basically any kind of mutable object will work.

There are several more detailed explanations in the
archives of this list if you search for them.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list