Totally Confused: Passing variables to functions

Achim Domma domma at procoders.net
Thu Jun 5 04:33:00 EDT 2003


"Chuck" <cdreward at riaa.com> wrote in message
news:m6ptdvg3p8dvcbpg7qhelb7s2i0slrk7b0 at 4ax.com...

Sorry for the encrypted message, here's the right on:

Hi Chuck,

> def blah(arg):
>     arg.append(3)
>
> v = [1,2]
>
> blah(v)

This confused me also the first time, but it's very consistent and
simple:

v is not the list, v is a reference to the list. From this point of
view, all values are passed by value, but your function gets a value
which is a reference.

> But it's not, because if I say "arg = None" inside the function,
> "v" is unchanged.

Of course, arg is another variable holding a reference to the same
list as v. What you do is asign a new value to arg, so there is no
reason why v should be changed.

> Also, if I do something similar:
>
> def blah(arg):
>     arg = arg + 1
>
> v = 1
>
> blah(v)

Same as above.

> It seems that if you pass a mutable variable, you can change it,
> but only by using it's methods, ie arg.append(), and NOT by doing
> an "arg = (new value)".

See above: arg.append uses the passed reference and changes the
underlying object. arg = (new value) asigns a reference to the new
value to arg.

> And if you pass an immutable variable, you can't change it at all.

I you know that you don't get an immutable variable, but rather a
reference to an immutable value this makes absolutly sense.

Achim






More information about the Python-list mailing list