I understand basic python references like the difference between a+=b and a=a+b, but this confuses me.
import numpy as np
arr1 = np.arange(6).reshape(2,3)
arr2 = arr1[0]
arr2 is arr1[0] #returns False, when I expect True
arr1[0] = [7,8,9]
arr2 #[7,8,9], when I expect [0,1,2] since the 'is' returned False
What's going on here?
Python passes arguments neither by reference nor by value, but by assignment.
A Python program accesses data values through references. A reference is a name that refers to the specific location in memory of a value (object). References take the form of variables, attributes, and items. In Python, a variable or other reference has no intrinsic type.
Python utilizes a system, which is known as “Call by Object Reference” or “Call by assignment”. In the event that you pass arguments like whole numbers, strings or tuples to a function, the passing is like call-by-value because you can not change the value of the immutable objects being passed to the function.
When you index the numpy array, you create a new view (which is itself a numpy array). This is a different object, so is
fails, but it's a view of the same piece of honestly-actually-on-the-hardware memory. When you modify that view, you therefore modify that bit of memory of which there may be another view.
Edit: You can actually see the start address of the memory associated with a numpy array by inspecting the ctypes.data
attribute of the array.
In [1]: import numpy as np
In [2]: arr1 = np.arange(6).reshape(2,3)
In [3]: arr2 = arr1[0]
In [4]: arr2.ctypes.data
Out[4]: 39390224
In [5]: arr1[0].ctypes.data
Out[5]: 39390224
The same!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With