Simple newbie question about parameters handling in functions (or am I dump or what?)

Tim Roberts timr at probo.com
Thu Feb 12 08:26:15 CET 2004


Niki Iv <niki_iv at abv.bg> wrote:
>
>Well this is my first Python day. I am tampering with functions. I
>read that parameters are passed by-value rather than by-reference. So
>function can change wathever parameters reffers to. My troube (well my
>presonal not understanding comes from this)

There were several responses to your post that pointed to articles that
will explain the technical details, but I decided to point out exactly
where your assumption goes wrong.

>MyList = ["Line 1","Line 2","Line 3"]
>print MyList
>ChangleList(MyList)
>print MyList

You need to separate the notion of "an object" from the notion of "a name".
Here, you create a list object that contains three strings.  You have a
name called MyList that is bound to that list.  When you call ChangeList,
you are passing that three-element list object to the function.

>(1)def ChangeList(ListToChange):
>(2)	ListToChange[1] = "Line B"
>(3)	ListToChange = ["Line X","Line Y","Line Z"]
>(4)	ListToChange[2] = "Line C"

At line (1), the local name ListToChange will be bound to the same
three-element list that is bound to MyList.  Both names are bound to the
same list.  Line (2) alters the second element of that list.

In line (3), however, you create a brand new list object with three string
elements, and bind that object to the name "ListToChange".  There are now
two separate three-element list objects, and this function no longer has
any link to the list that is bound to the global MyList.  In line (4),
then, we alter the third element of this new list.  MyList remains
unchanged.  The function ends without doing anything with ListToChange, so
the new list (which contains ["Line X","Line Y","Line C"]) will be deleted
during garbage collection.

>Result is unexpected
>["Line 1","Line 2","Line 3"]
>["Line 1","Line B","Line 3"]
>
>The last line in function is to change where ListToChange[2] reffers
>to.. but string is the same..
>Frankly I was expecting that ListToChange will change it's second
>(zero base) element... but it does not.

Sure, it does!  Print ListToChange at the end of your function, and you'll
see that.  However, ListToChange at that point is bound to a brand-new
list, so altering it has no global effect.
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list