[SciPy-user] fancy indexing and +=

Robert Kern robert.kern at gmail.com
Fri Sep 1 16:43:26 CDT 2006


A. M. Archibald wrote:
> Hi,
> 
> I'm trying to figure out how to use fancy indexing for ordinary
> (non-sparse) arrays. On reading, it's clear enough what is meant:
> 
> a = arange(3)
> a[[1,1,2]]
> -> array([1,1,2])
> 
> But when writing it's not so clear what should happen:
> 
> a[[1,1,2]] = array([1,2,3])
> a
> -> array([0,2,3])
> 
> All right, the assignment a[1]=... has been done twice, so I only see
> the effects of the second. Fair enough. But:
> 
> a[[1,1,2]] += 1
> a
> -> array([0,3,4])
> 
> That is, a[[1,1,2]] += 1 is equivalent to
> 
> a[[1,1,2]] = a[[1,1,2]] + 1
> 
> and not
> 
> for i in [1,1,2]:
>     a[i]+=1
> 
> Is this really intended? It's surprising, it seems like that forces
> numpy to make a copy, and it leaves me with the question of how to
> implement the second without a loop...

We've gone over this before on the numpy-discussion list. Given the way that 
Python implements augmented assignment, there is no way for the array object to 
know that you wanted to do some kind of loop. Python implements that statement 
as something equivalent to

   tmp = a.__getitem__([1,1,2])
   tmp.__iadd__(1)
   a.__setitem__([1,1,2], tmp)

There is no place to implement the kind of loop that you want to see.

Nor should we. According to the reference manual, augmented assignment methods 
should be implemented such that

   x += y

is nearly equivalent to

   x = x + y

with the exception of possible in-place modification of x.

   http://docs.python.org/ref/augassign.html

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
  that is made terrible by our own mad attempt to interpret it as though it had
  an underlying truth."
   -- Umberto Eco


More information about the SciPy-user mailing list