[Tutor] Confused about functions

Remco Gerlich scarblac@pino.selwerd.nl
Thu, 1 Nov 2001 19:19:20 +0100


On  0, Titu Kim <kimtitu@yahoo.com> wrote:
> I am making these statement without refering to the
> source. If i am wrong, please correct me. 
>     To explain the behaviour in changer(), i believe
> python by default passes changer a copy of x, but an
> object reference to the list L. Thus, changer makes
> change on the copy of x but changes the original list
> L. 

That's not true. Python always passes a reference of every object.

so in a function:

def func(x, y):
   x = 3
   y[0] = 3
   
a = 2
b = [2]

func(a,b)


In this function, x and y initially refer to the same objects as a and b,
since their references are passed to the function.

However, after 'x = 2', the local variable refers to a new object, 3. a is
unchanged, since it still refers to the old object, 2.

After 'y[0] = 3' however, y still refers to the same list, but the inside of
the list is changed. So b is also changed - it's the same list.

It's really the difference between letting a local name refer to a new
object, and changing an object.

-- 
Remco Gerlich