[SciPy-user] temporary copies for in-place array modification?

Robert Kern robert.kern at gmail.com
Mon Jul 28 12:13:24 EDT 2008


On Mon, Jul 28, 2008 at 06:41, Steve Schmerler <elcorto at gmx.net> wrote:
> Hi all
>
> Say I do this:
>
>    >>> a
>    array([1, 2, 3, 4, 5, 6])
>
>    >>> a[1:] = a[1:] - a[:-1]

The right-hand side of this will be a temporary array.

>    >>> a
>    array([1, 1, 1, 1, 1, 1])
>
>    >>> b = a[1:]
>    >>> ...
>
> I.e. I want to compute the difference of a's elements and store them in place
> in b = a[1:] to work with that (b is only a view so that's ok, no copy).
>
> Are there any temp copies of `a` involved? I ask b/c `a` will be large.
> Thanks!

Unfortunately, a temporary is unavoidable. If you modify `a` in-place,
you will mess up the computation. For example, we could try using the
third argument to the subtract() ufunc to place the results back into
a[1:]:

In [1]: import numpy

In [2]: a = numpy.arange(1,7)

In [3]: numpy.subtract(a[1:], a[:-1], a[1:])
Out[3]: array([1, 2, 2, 3, 3])

-- 
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