Passing by reference

Michael Sparks ms at cerenity.org
Thu Dec 20 16:50:14 EST 2007


MartinRinehart at gmail.com wrote:

> ... the first element of the list to which x refers is a reference to
> the new string and back outside foo, the first element of the list to
> which x refers will be a reference to the new string.

I'd rephrase that as:
   * Both the global context and the inside of foo see the same list
   * They can therefore both update the list
   * If a new string is put in the first element of the list, the can
     both see the same new string.

> Right?

You know you can get python to answer your question - yes? Might be slightly
more illuminating than twisting round english... :-)

OK, you're passing in a string in a list. You have 2 obvious ways of doing
that - either as an argument:

def foo(y):
    y[0] += " other"
    print id(y[0])

... or as a global: (which of course you wouldn't do :-)

def bar():
    global x
    x[0] += " another"
    print id(x[0])

So let's see what happens.

>>> x = ["some string"]  # create container with string
>>> x[0]      # Check that looks good & it does
'some string'
>>> id(x[0])  # What's the id of that string??
3082578144L
>>> foo(x)    # OK, foo thinks the new string has the following id
3082534160
>>> x[0]      # Yep, our x[0] has updated, as expected.
'some string other'
>>> id(x[0])  # Not only that the string has the same id.
3082534160L
>>> bar()     # Update the global var, next line is new id
3082543416
>>> x[0]      # Check the value's updated as expected
'some string other another'
>>> id(x[0])  # Note that the id is the same as the output from bar
3082543416L

Does that perhaps answer your question more precisely ?


Michael.







More information about the Python-list mailing list