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

Emile van Sebille emile at fenx.com
Wed Aug 22 18:10:57 EDT 2001


You never return anything from your functions, so the only way x or y will
change is by x or y being mutable and not local.  This only happens in f2
when you call it.  Try adding a return x,y to f1 and f3 and invoke them as
x,y = f1(x,y) to see what happens.

HTH,

--

Emile van Sebille
emile at fenx.com


> >>> 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]
>
> >>> x = 1
> >>> y = 2
> >>> f1(x,y)
> 1  -  2
> >>> print x, " - ", y
> 1  -  2
> >>> x = [1]
> >>> y = [2]
> >>> f2(x,y)
> [1]  -  [2]
> >>> print x, " - ", y
> [1, 2]  -  [2, -2]
> >>> f3(x,y)
> [1, 2]  -  [2, -2]
> >>> print x, " - ", y
> [1, 2]  -  [2, -2]
> >>>
>
>




More information about the Python-list mailing list