Thanks for your valuable feedback guys.
Cheers
Hans
-----Original Message-----
From: w chun [mailto:wescpy at gmail.com]
Sent: Tuesday, 6 December 2005 9:11 p.m.
To: Hans Dushanthakumar
Cc: tutor at python.org
Subject: Re: How to Pass lists by value
On 12/5/05, Kent Johnson <kent37 at tds.net> wrote:
>> You have to change how you think about variables. In Python, a
> variable is not a storage location into which values are put, it is a
> reference to an object - a name given to an object. Assignment binds a
> name to a value.
>> When you call a function, the names of the formal parameters are bound
> to the values passed in to the function. Parameters are *always*
> passed by reference.
hans,
kent makes some good points here that you need to master. to further
elaborate, here are three things to keep in mind:
1) in Python, everything is an object, and all names are just references
or aliases to those objects.
2) managing these objects is based on how many references exist that
point to an object -- this is called a "reference count." objects are
"deallocated" when an object's reference count goes to zero.
3) there are both mutable (can be changed) and immutable (cannot be
changed without creating a new one) objects. lists and dictionaries are
mutable while numbers, strings, and tuples are not.
in your example, you passed in a list by reference. that list had a
reference count of 1 when you created it; when you passed it to the
function, a new reference, local to the called function, is created for
that object, incrementing its reference count by 1, and now it totals 2.
(a side note here: that only mutable objects have methods.) you then
called a method [[].append()] which alters that object, which it did.
in the function, you only had access to the 2nd alias to the list, but
it doesn't matter whether you used this one, or called the list's method
from the global code using the original reference as either would affect
the list the way it did. note that when the function concluded, the
local variable went away, decrementing the list object's reference count
back down to 1.
in your second example, you almost did the exact same thing. you
*did* pass the list in as an argument, creating another reference to the
list object, incrementing its reference count to 2. but in this case,
you immediately "wiped" access to that object by reassigning that
variable name to point to something else, an integer. all you did here
was to decrement the reference count to the list object by one (back to
1). the outer print gave the expected output because you just passed
that integer object back to the calling function.
hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "Core Python
Programming", Prentice Hall, (c)2006,2001
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca http://cyberwebconsulting.com