Numeric, how to do in place full-array modification?

Eric Jacobs x at x.x
Sat Oct 2 22:52:38 EDT 1999


Ionel Simionescu wrote:
> 
> Hi,
> 
> I want to do the following:
> 
> for t in range( T ):
>    net = dot( C, x )
>    x   = A*net*(1-net)
> 
> Because these arrays might turn to be large, I want to pre-alloate <net> and
> write both <net> and <x> in place rather than creating new arrays.
> 
> Intuitively, I would write it like:
> 
> net = zeros(shape, typecode)
> for t in range( T ):
>     net[:] = dot( C, x)
>     x[:]   = A*net*(1-net)
> 
> But, I recall that, when on the right hand side, a[:] is used precisely to
> create a new sequence. Therefore, I'm unclear about the semantics of this
> form.

Your intuition is correct. a[:] indicates a slice of a sequence. On the
right
side, it will create a subsequence (in this case it will create the
whole
sequence, because no indices were supplied.) On the left side, it
indicates
which subsequence of a we're going to be assigning to (in this case, the
whole sequence.) So, yes, this is legal python and it does have the
intended
effect of modifying the array in place.

Incidentally, you don't need to preinitialize the lists to anything
special:
net = [] will work just fine.

But I question why you would want to do it this way at all. Using the
slice
operator on the left hand side is not going to avoid creating new
arrays.
The function dot() and the * operator in your example create new arrays
anyway and return them in both cases. Might as well just put that newly
returned array in your variable and let python deallocate the old one,
rather than spend time moving each element back.

I just checked with the profiler and some simple functions and the
second
way was about 20-50% slower.

The only time you'd really need to use the a[:] = ... form is if you
want
to "mute" a mutable type (is that the right verb?)

>> a = [1,2,3]
>> b = a
>> a[:] = [6,7,8]

and you want "b" to change also.

Also, the a[x:y] = ... form will be more efficient if you need to change
a
small part of the sequence.




More information about the Python-list mailing list