Totally Confused: Passing variables to functions

Asun Friere afriere at yahoo.co.uk
Thu Jun 5 23:55:36 EDT 2003


Chuck <cdreward at riaa.com> wrote in message news:<m6ptdvg3p8dvcbpg7qhelb7s2i0slrk7b0 at 4ax.com>...
> 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.
> 

You don't even need to consider functions to understand what is
happening here.    Your problem is that the assignment to arg changes
what it 'points' to.  Consider the following scenario.

>>>sys.ps1 = '? '; sys.ps2 = '= ' #for those reading news on the web
? a = "hello navel"
? #create a 'reference' 'a' to the string "hello navel'
? b = a
? #'b' now 'points' to the same string
? b
'hello navel'
? b = 5
? #change where 'b' points to
? b
5
? #but 'a' still points to the string
? a
'hello navel'
? a = 'some completely different string'
? #change where 'a' points to.   The last reference to the string \
= is now gone, and the string awaits garbage collection.

Similarly in your example:  'arg' does point to the argument with
which your function was called and it does so until such time as you
tell it to point elsewhere, (as you did, when you wrote 'arg = None').




More information about the Python-list mailing list