Totally Confused: Passing variables to functions

Chuck cdreward at riaa.com
Thu Jun 5 03:10:00 EDT 2003


I've hit a stumbling block while trying to pick up Python. I've googled
around, and I don't think I'm the first to have this question, but I haven't
been able to find an answer that explains things for me.

def blah(arg):
    arg.append(3)

v = [1,2]

blah(v)

... This gives me the impression that Python passes variables by reference (by
a "pointer"), and the "arg" in blah is the same as "v".

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

Also, if I do something similar:

def blah(arg):
    arg = arg + 1

v = 1

blah(v)

I get the impression Python passes variables by copy.

*Huh?*

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)".

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

This doesn't seem very intuitive, which leads me to believe I'm missing "the
big picture".

In the python tutorial, it says:

   Actually, call by object reference would be a better description,
   since if a mutable object is passed, the caller will see any changes
   the callee makes to it (items inserted into a list).

But I don't understand what "object reference" means. I'm familiar with "pass
by copy" and "by reference(pointer)" in the Pascal or C languages...

What's going on? (*grin*)


Thanks!




More information about the Python-list mailing list