Totally Confused: Passing variables to functions
steve.horsley at cwcom.cwplc.com
Fri Jun 6 18:34:27 CEST 2003
Chuck <cdreward at riaa.com> wrote in message news:<i39udvo7e11828rkmudo93hj3dr68bft95 at 4ax.com>...
> > >>> 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"?
> 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
> It seems to say, "arg now points to what v also points to".. is this correct?
Spot on. Exactly. Except some people may prefer to say "refers to"
rather than saying "points to". The one list now has two references
> 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?
Yes. In python, even the number 1 is a object - a number sort of object.
and see how many functions the number 1 has!
Then try (note the space before the dot):
>>> 1 .__hex__
<method-wrapper object at 0x007B5BD0>
>>> 1 .__hex__()
But the fact that numbers are objects is something of a diversion here.
Let's try this:
# This appends to the list that arg refers to
# make arg refer to something completely different
arg = 42
# make a list and a variable 'a' that refers to it
a = ['one', 'two']
# make a new variable 'b' and point it at the same
# list as that a refers to
b = a
# call foo, which will append to our list
# (and also fiddle with a different list of its own)
# remove one of the references to our list
# remove the other reference to our list.
# Poof! the list gets garbage collected because no-one has a
# reference to it any more. It's gone and forgotten.
> If so, I *think* I'm starting to "get it"... ;-)
I'm sure you are.
More information about the Python-list