questions regarding assignement and copy

A. M. Archibald peridot.faceted at
Wed Oct 18 10:08:15 CDT 2006

On 18/10/06, David Cournapeau <david at> wrote:
> Sven Schreiber wrote:
> >
> > Yes it's intended; as far as I understand the python/numpy syntax, <+>
> > is an operator, and that triggers assignment by copy (even if you do
> > something trivial as bar = +foo, you get a copy, if I'm not mistaken),
> >
> So basically, whenever you have
> foo = expr
> with expr is a numpy expression containing foo, you trigger a copy ?

No. "=" never copies, but "+" does: when you do "A+B" you produce a
new, freshly-allocated array, which you can then store (a reference
to) in any variable you like, including A or B. So

M = M+1

makes a copy because "M+1" is a new matrix, which you are assigning to
M. Unfortunately, this means if you do:

M = 2*(M+1)

python makes the new matrix M+1, then makes the new matrix 2*(M+1),
discards M+1, and sets M to point to 2*(M+1). If you want to avoid all
this copying, you can use python's in-place operators:

M += 1
M *= 2

This is actually a standard difficulty people have with python, made
more obvious because you're working with mutable arrays rather than
immutable scalars.

A. M. Archibald

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