By value or by reference?

JCM joshway_without_spam at myway.com
Mon Oct 18 18:35:51 CEST 2004


Oliver Fromme <olli at haluter.fromme.com> wrote:
...
>  > > > > def foo(a): a = 1
>  > ...
>  > > > > i = 10
>  > > > > foo(i)
>  > > > > print i
>  > 
>  > With pass-by-reference, i would now be 1.  However, since python is
>  > pass-by-value, it remains 10.

> It remains 10 because integers are immutable, so the function
> code cannot modify the caller's variable anyway.  However, if
> you pass a mutable variable, things look a little different:

It doesn't matter that integers are immutable.  Rebinding formal
parameters cannot change variables in the callers scope.

>>>> def foo(a): a[0] = 1
> ...
>>>> i = [10]
>>>> foo(i)
>>>> print i
> [1]

In this case, you're dereferencing the list (I'm using pointer-
terminolgy, but I'm still talking about the behavior of the language,
not its implemenation).  You're basically modifying the object passed
into the function, not rebinding a variable.



More information about the Python-list mailing list