Numeric array referencing vs copying.

Maarten van Reeuwijk maarten at remove_this_ws.tn.tudelft.nl
Sun Feb 1 13:48:23 CET 2004


Hello,

I recently started using Python for CFD postprocessing, and although I like
the language very much, it's memory management (copying vs referencing)
makes me a little paranoid sometimes. Could you clarify how this works in
Python?

- does the array constructor make a copy of the elements?
- is a[:] = b[:] different from a = b?

Some good examples are in the fragment below:

from Numeric import *

def el_changebase(vecfield, newbase):
   """ Changes the base of the vectorfield. newbase is a list containing the
       new basevectors(which are an 1D-array). vecfield is a list containing
       the fields for the individual vector components fields. The lenght of
       the vecfield and newbase lists must be identical. """

   vf = vecfield
   nb = newbase
   nf = []

   tmp = array(vf[0], vf[0].typecode(), savespace = 1)

   for bcomp in range(len(newbase)):
      tmp[:] = 0
      for vcomp in range(len(newbase)):
         tmp = tmp + nb[bcomp][vcomp] * vf[vcomp]

      nf.append(array(tmp))

   return nf

# sample run
u = arange(9)
u.shape = (3,3)
v = array(u)

print "before:\n", u, "\n", v

s2 = 0.5 * sqrt(2)

# rotate the coordinate system 45 degrees
u, v = el_changebase([u,v],[array((s2, s2)), array((s2, -s2))])

print "after:\n", u, "\n",  v

TIA, Maarten

-- 
===================================================================
Maarten van Reeuwijk                    Thermal and Fluids Sciences
Phd student                             dept. of Multiscale Physics
www.ws.tn.tudelft.nl                 Delft University of Technology



More information about the Python-list mailing list