Totally Confused: Passing variables to functions

Aldo Cortesi aldo at nullcube.com
Thu Jun 5 08:23:19 EDT 2003


Thus spake Chuck (cdreward at riaa.com):

> I'm new here...
> 
> >  >>> v = [1,2]
> >  >>> arg = v
> >  >>> arg.append(3)
> >  >>> v
> >  [1, 2, 3]
> 
> I'm not "getting" variables in Python, then.
> 
> What exactly happens when I say "arg = v"?

"v" is just a label, which points at the list [1, 2]. You
then set another label, "arg", equal to "v". You now have
two labels pointing at the same list. Python objects exist
quite independently from the labels that point at them, with
the sole caveat that when no more labels point at an object,
it is destroyed. 

Here's a nice little post by Guido explaining all this
graphically:

http://tinyurl.com/djbc


> Not "arg is assigned the value [1,2] that v happens to hold"...
> 
> Not "arg now points to v" (can't be, since you can delete v and arg still
> exists)

No - "arg" and "v" simply both point to the list, which has
an independent existence. When we go:

del v

we are simply unbinding the label "v" from the list. Since a
reference to the list is still being held by "arg", the list
itself remains in existence.

> It seems to say, "arg now points to what v also points to".. is this correct?
> 
> And so...
> 
> a = 1
> b = a
> 
> is really saying, "b points to what a points to, which is a 'variable' with
> the value of 1, which cannot be changed (immutable)".
> 
> Is this correct?
> 
> If so, I *think* I'm starting to "get it"...  ;-)

That's right. You've got it. 





Aldo



-- 
Aldo Cortesi
aldo at nullcube.com
http://www.nullcube.com





More information about the Python-list mailing list