Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Making sense of references

Tags:

python

numpy

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?

like image 529
countunique Avatar asked May 21 '13 16:05

countunique


People also ask

Does Python pass everything by reference?

Python passes arguments neither by reference nor by value, but by assignment.

How does Python referencing work?

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.

Is Python by reference or copy?

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.


1 Answers

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!

like image 152
Henry Gomersall Avatar answered Nov 15 '22 06:11

Henry Gomersall