[Numpy-discussion] advanced indexing question

Sebastian Berg sebastian at sipsolutions.net
Wed Feb 4 03:03:14 EST 2015


On Mi, 2015-02-04 at 07:22 +0000, David Kershaw wrote:
> The numpy reference manual, array objects/indexing/advance indexing, 
> says: 
> Advanced indexing always returns a copy of the data (contrast with 
> basic slicing that returns a view).
> 
> If I run the following code:
>  import numpy as np
>  d=range[2]
>  x=np.arange(36).reshape(3,2,3,2)
>  y=x[:,d,:,d]
>  y+=1
>  print x
>  x[:,d,:,d]+=1
>  print x
> then the first print x shows that x is unchanged as it should be since y 
> was a copy, not a view, but the second print x shows that all the elements 
> of x with 1st index = 3rd index are now 1 bigger. Why did the left side of
>  x[:,d,:,d]+=1
> act like a view and not a copy?
> 

Python has a mechanism both for getting an item and for setting an item.
The latter will end up doing this (python already does this for us):
x[:,d,:,d] = x[:,d,:,d] + 1
so there is an item assignment going on (__setitem__ not __getitem__)

- Sebastian


> Thanks,
> David
> 
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
> 

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20150204/f490e493/attachment.sig>


More information about the NumPy-Discussion mailing list