How does Python (v2.1.1) handle parameter passing? By value or by reference?

Ignacio Vazquez-Abrams ignacio at openservices.net
Wed Aug 22 18:24:30 EDT 2001


On Wed, 22 Aug 2001, Rob van Wees wrote:

> Hi all,
>
> As a newbie to Python, I'm having trouble finding out how the interpreter
> handles parameters that are passed to functions. Sometimes they seem to be
> handled as values and sometimes as references.
>
> The Python documentation does not seem to answer my question. Could any of
> you help me?
>
> Below is a copy of an IDLE session to find out what Python does with
> parameters. It shows the different behaviors of the interpreter. I defined 3
> functions that print and then change the parameters to see the effects on x
> and y. The results seem weird to me. Anyone knows what is happening here?
>
> TIA,
>
> Rob.

If you look very closely, it appears that it passes them by object reference.
I've changed your variable names for clarity.

> --------------------------------------- IDLE session
> below ---------------------------------------
>
> Python 2.1.1 (#20, Jul 20 2001, 01:19:29) [MSC 32 bit (Intel)] on win32
> Type "copyright", "credits" or "license" for more information.
> IDLE 0.8 -- press F1 for help
> >>> def f1(x,y):
>                 print x, " - ", y
>                 x = x + 2
>                 y = y - 2
>
> >>> def f2(x, y):
>             print x, " - ", y
>             x.append(2)
>             y.append(-2)
>
>
> >>> def f3(x,y):
>             print x, " - ", y
>             x = [1,2,3,4]
>             y = [4,3,2,1]
>
> >>> a = 1
> >>> b = 2
> >>> f1(a,b)
> 1  -  2
> >>> print a, " - ", b
> 1  -  2

x and y are assigned new values, so nothing happens out here.

> >>> a = [1]
> >>> b = [2]
> >>> f2(a,b)
> [1]  -  [2]
> >>> print a, " - ", b
> [1, 2]  -  [2, -2]

Methods of x and y are called that change their value, so they change out here
too.

> >>> f3(a,b)
> [1, 2]  -  [2, -2]
> >>> print a, " - ", b
> [1, 2]  -  [2, -2]

x and y are assigned new values, so nothing happens out here.

HTH

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>







More information about the Python-list mailing list