Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reference of a single numpy array element

Tags:

python

numpy

Lets say I have a numpy array like

x = np.arange(10)

is it somehow possible to create a reference to a single element i.e.

y = create_a_reference_to(x[3])
y = 100 
print x
[  0   1   2 100   4   5   6   7   8   9]
like image 396
jrsm Avatar asked May 14 '14 11:05

jrsm


2 Answers

You can't create a reference to a single element, but you can get a view over that single element:

>>> x = numpy.arange(10)
>>> y = x[3:4]
>>> y[0] = 100
>>> x
array([0, 1, 2, 100, 4, 5, 6, 7, 8, 9])

The reason you can't do the former is that everything in python is a reference. By doing y = 100, you're modifying what y points to - not it's value.

If you really want to, you can get that behaviour on instance attributes by using properties. Note this is only possible because the python data model specifies additional operations while accessing class attributes - it's not possible to get this behaviour for variables.

like image 57
loopbackbee Avatar answered Sep 19 '22 11:09

loopbackbee


No you cannot do that, and that is by design.

Numpy arrays are of type numpy.ndarray. Individual items in it can be accessed with numpy.ndarray.item which does "copy an element of an array to a standard Python scalar and return it".

I'm guessing numpy returns a copy instead of direct reference to the element to prevent mutability of numpy items outside of numpy's own implementation.

Just as a thoughtgame, let's assume this wouldn't be the case and you would be allowed to get reference to individual items. Then what would happen if: numpy was in the midle of calculation and you altered an individual intime in another thread?

like image 36
jsalonen Avatar answered Sep 20 '22 11:09

jsalonen