[SciPy-user] += has strange behavior with multidimensional arrays

Robert Kern robert.kern@gmail....
Wed Dec 5 19:04:35 CST 2007

Erik Volz wrote:
> Sorry if this issue is already well-known.
> It seems that += and perhaps *= operators do not have correct behavior
> with multidimensional arrays.

Well, let's be more clear. It does not have the desired behavior when the RHS
contains a view of the array on the LHS. Otherwise, the behavior is correct.
Multidimensionality has nothing to do with it.

> Let's say I want to make a simple matrix symmetric across the diagonal.
> from pylab import *
> y = ones((10,10)) * arange(1,11)
> print y
> yy = y
> print 'This is incorrect:'
> y+=transpose(y); print y
> print 'But this still works:'
> yy = yy+transpose(yy); print yy
> Clearly python is modifying the array element by element, not
> simultaneously. You might not consider this a bug, but the behavior is
> so unintuitive (and unlike matlab) that it would trip up most people.

It's a straightforward consequence of inplace modification and views. It's not
what you want in this case, but there is no way for Python or numpy to know
this. To get what you want, you have to give up one or the other. Above, you
gave up inplace modification. The other approach is to make a copy:

  y += array(y.T)

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