Is it possible to pass a parameter by reference?

Tim Roberts timr at probo.com
Sun Feb 27 02:49:26 EST 2005


Anthony Liu <antonyliu2002 at yahoo.com> wrote:
>
>I defined two functions, f1 and f2.  
>
>f1 modifies the value of a variable called apple.
>
>I want to pass the modified value of apple to f2.
>
>How can I do this?  I got stuck.

It depends on the data type.  Essentially, all objects are passed by
reference.  However, some objects can be modified, and some cannot.  Lists
can, strings and tuples cannot.

This is one of the most important thing to understand about Python, in my
opinion.  There is a fundamental separation between an object and whatever
names it is known by.

Here's an example:

   def xxx(yyy):
      yyy[1] = 3

   zzz = [ 0, 1, 2 ]
   xxx(zzz)

After this code runs, zzz will be [0,3,2].  Note that, while xxx is
running, the list that was created as [0,1,2] has two names.

However, this code will fail within xxx, because the string cannot be
modified:
   aaa = "abcde"
   xxx(aaa)

However, watch this:

   def xxx(yyy):        # 0
      yyy = [ 3, 4, 5]  # 1

   zzz = [ 0, 1, 2 ]    # 2
   xxx(zzz)             # 3

After this runs, zzz will still be [0,1,2].  At line 2, a list object is
created containing [0,1,2].  The variable name zzz is bound to that list.
When we get to lines 3 and 0, the variable name yyy within function xxx is
bound to that exact same object.

However, in line 1, a NEW list object is created, containing [3,4,5].  The
variable yyy is then bound to this NEW object, and its binding to the other
list is lost.  However, the variable zzz is still bound to [0,1,2].

If you need to create a new object and return it to the mainline, do that:

    def xxx(yyy):
        yyy = [ 3, 4, 5 ]
        return yyy

    zzz = [ 0, 1, 2 ]
    zzz = xxx(zzz)
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list