questions regarding assignement and copy

Robert Kern robert.kern at
Wed Oct 18 12:12:37 CDT 2006

David Cournapeau wrote:

>     bar   += 1
>     print bar is foo
>     prints True
>     But if I do bar = bar + 1, then bar is not a copy of foo anymore. Is 
> this intended ?

Yes, very much so! If it were otherwise Guido would never have added the 
augmented assignment operators. From the reference manual:

"""An augmented assignment expression like x += 1 can be rewritten as x = x + 1 
to achieve a similar, but not exactly equal effect. In the augmented version, x 
is only evaluated once. Also, when possible, the actual operation is performed 
in-place, meaning that rather than creating a new object and assigning that to 
the target, the old object is modified instead."""

> This looks really confusing to me, and I would like to 
> know what the precise rules about copy vs alias are ?

I'm not going to go through all of the functions in numpy, but here are some 
(unorganized) rules of thumb:

* Any operations with regular operators + - / * // ** ~ ^ & | << >> < > == <=, 
etc. will put their results into new arrays. If the expression is on the RHS of 
a regular assignment, just ignore the LHS of the assignment; even if the name on 
the LHS is the same as a name on the RHS, the expression is evaluated, the new 
array is created and *then* the new array is assigned to the LHS name.

* Augmented assignment operators will operate in-place.

* Functions and methods should state that they operate in-place in their docstrings.

* The asarray(), asanyarray(), etc. functions will return the input array if it 
is already suitable.

* Slicing, reshaping, transposing and similar structural operations create new 
array objects, but they are generally views, not copies of the data.

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

Using Tomcat but need to do more? Need to support web services, security?
Get stuff done quickly with pre-integrated technology to make your job easier
Download IBM WebSphere Application Server v.1.0.1 based on Apache Geronimo

More information about the Numpy-discussion mailing list