1

Possible Duplicate:
Python: How do I pass a variable by reference?

I want to test the parameter passing behavior in python function by the following 2 functions:

In:

def f(a):
        a[0]=3
        print 'in f ',a
a=[1,2]
print 'ori ',a
f(a)
print 'now ',a

It turned out the "a" has been modified after returning from f().

However, in:

import numpy as np
def f(a):
        a=np.array(a,np.float)
        print 'in f ',a
a=[1,2]
print 'ori ',a
f(a)
print 'now ',a

I found that "a" was not changed to numpy array after returning from f().

Can somebody give some explanations?

Community
  • 1
  • 1
Hailiang Zhang
  • 17,604
  • 23
  • 71
  • 117
  • 5
    I'm sure one of the dozen or so duplicates can. – Ignacio Vazquez-Abrams Jan 07 '12 at 04:43
  • oh, you modified the code. Even now `a` is not converted because you asigned the name `a` in the function to a numpy array (overwriting the old name and losing the reference) and you did not return it – joaquin Jan 07 '12 at 04:55
  • In short, Python uses [call by sharing](https://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_sharing). – icktoofay Jan 07 '12 at 04:58
  • well, at least nobody is downvoting the OP. I think he does not realize how dangerous his position is. – joaquin Jan 07 '12 at 05:04

1 Answers1

4

I see this a lot so it must've been already answered but here's my take.

The two lines:

a[0]=3

and

a=np.array(a,np.float)

do something completely different. The first one doesn't change what a is -- it still is the same list after this line. It merlely sets a new object at index 0 of the list. We say that it mutates it.

The second line binds a new object to the function's local a variable. From that point on, a inside the function references a different object. The a outside of the function is completely separate so it still points to the list. Both a's simply reference the same object initially.

You can't re-bind names outside of the function like this. There are multiple ways to circumvent this, one of them is to return the new object and let the caller bind the return value back to its own a.

yak
  • 8,851
  • 2
  • 29
  • 23