# Numeric array referencing vs copying.

John J. Lee jjl at pobox.com
Mon Feb 2 01:10:12 CET 2004

```Maarten van Reeuwijk <maarten at remove_this_ws.tn.tudelft.nl> writes:

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

You mean Numeric.array?  Yes.  Try it out with the interactive prompt:

>>> a = arange(3.)
>>> a
array([ 0.,  1.,  2.])
>>> b = array(a)
>>> b
array([ 0.,  1.,  2.])
>>> id(a)
135849936
>>> id(b)
135622560
>>> a[0] = 5.
>>> a
array([ 5.,  1.,  2.])
>>> b
array([ 0.,  1.,  2.])

> - is a[:] = b[:] different from a = b?
[...]

Yes, completely.  a = b means just the same as it means for any other
"assignment" in Python: it just binds (the object bound to the name b)
to the name a.  It never means anything else in Python, happily :-)
There's a FAQ item (or two) on this in the Python FAQ.  It's very F'ly
A'd :-)

Slicing a Numeric array *is* different to other Python sequences:
slicing a Numeric.array doesn't make a copy, slicing a list (or a
tuple, of course) does.  I'm sure this is covered in the Numeric
manual, though it's a while since I read it.  Carrying on from above:

>>> c = a[:]
>>> c
array([ 5.,  1.,  2.])
>>> c[0] = 0
>>> c
array([ 0.,  1.,  2.])
>>> a
array([ 0.,  1.,  2.])

But, in contrast:

>>> l = [0., 1., 2.]
>>> l2 = l[:]
>>> l2
[0.0, 1.0, 2.0]
>>> l2[0] = 5
>>> l2
[5, 1.0, 2.0]
>>> l
[0.0, 1.0, 2.0]

John

```