I'm new to Python. From my friends, I learned that in python, parameter passing to a function is similar to call-by-reference in C++. But after some testing with NumPy, I saw some behaviors I cannot easily understand.
As an example, I made the following code.
#!/usr/bin/python
import numpy as np
def InitArray(x):
x = np.arange(0, 5)
def ChangeValue(x):
x[2] = 4
def main():
x = np.array([1, 2, 3])
print x
InitArray(x)
print x
ChangeValue(x)
print x
if __name__ == "__main__":
main()
My expectation is after calling InitArray, the array 'x' should have changed to np.array([0, 1, 2, 3, 4])
, but it turns out that it's not.
But when I call ChangeValue(x), the value is actually changed. So, the following is the result.
[1 2 3]
[1 2 3]
[1 2 4]
What I don't understand is why the value didn't become [0, 1, 2, 3, 4]
after calling InitArray?