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?
I see this a lot so it must’ve been already answered but here’s my take.
The two lines:
and
do something completely different. The first one doesn’t change what
ais — 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
avariable. From that point on,ainside the function references a different object. Theaoutside of the function is completely separate so it still points to the list. Botha‘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.