# [Numpy-discussion] Inplace index suprise

Lisandro Dalcin dalcinl@gmail....
Thu Mar 20 16:43:21 CDT 2008

```I think you are wrong, here THERE ARE tmp arrays involved... numpy has
to copy data if indices are not contiguous or strides (in the sense of
actually using a slice)

In [1]: from numpy import *
In [2]: A = array([0,0,0])
In [3]: B = A[[0,1,2]]
In [4]: print B.base
None
In [5]: C = A[0:3]
In [6]: print C.base
[0 0 0]

On 3/20/08, Gael Varoquaux <gael.varoquaux@normalesup.org> wrote:
> On Thu, Mar 20, 2008 at 05:42:05PM +0000, James Philbin wrote:
>  > I was suprised to see this result:
>  > >>> import numpy as N
>  > >>> A = N.array([0,0,0])
>  > >>> A[[0,1,1,2]]+=1
>  > >>> A
>  > array([1, 1, 1])
>
>  > Is this expected? Working on the principle of least surprise I would
>  > expect [1,2,1] to be output.
>
>
> This is a FAQ. This cannot work, because the inplace operation does not
>  take place as a for loop. It is a "one shot" operation, that happens "at
>  once". Let me rephrase this: you can think of this as a two phase
>  operation:
>
>     1) first you the indices of you want to modify
>
>         B = A[[0, 1, 1, 2]]
>
>         thus B = array([0, 0, 0, 0)]
>
>     2) then you add one to these:
>
>         C = B + 1 = array([1, 1, 1, 1])
>
>     3) then you assign these in the indices you are interested in:
>
>         A[[0, 1, 1, 2]] = C
>
>  Actually, there is no copy going, so B and C do not exist as temporary
>  arrays, but this is the idea: the operations are happening at once over
>  the whole array.
>
>  HTH,
>
>  Gaël
>
> _______________________________________________
>  Numpy-discussion mailing list
>  Numpy-discussion@scipy.org
>  http://projects.scipy.org/mailman/listinfo/numpy-discussion
>

--
Lisandro Dalcín
---------------
Centro Internacional de Métodos Computacionales en Ingeniería (CIMEC)
Instituto de Desarrollo Tecnológico para la Industria Química (INTEC)
Consejo Nacional de Investigaciones Científicas y Técnicas (CONICET)
PTLC - Güemes 3450, (3000) Santa Fe, Argentina
Tel/Fax: +54-(0)342-451.1594
```