[Numpy-discussion] Confusion regarding Numeric array resizing

David M. Cooke cookedm at physics.mcmaster.ca
Thu Aug 26 21:52:09 EDT 2004

On Thu, Aug 26, 2004 at 10:19:15PM -0400, Jp Calderone wrote:
>   I'm confused by the restriction on resizing arrays demonstrated below:
> >>> from Numeric import array
> >>> a = array([0])
> >>> a.resize((2,))
> >>> b = a
> >>> a.resize((3,))
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
> ValueError: cannot resize an array that has been referenced or is 
> referencing another array in this way.  Use the resize function.
> >>> del b
> >>> a.resize((3,))
> >>> a
> array([0, 0, 0])
>   This seems like an unnecessary restriction.  Is there a reason I'm 
> missing for it to be in place?

In this case it's obvious that b is not a copy of a (because that's how
Python assignment works), but if your statement was b = a[1:], it's a
little different.  Then, b is a view of a: a[1] = 1 will make b[0] == 1.
So, the question is, how should resizing a change b? The Numeric
developers decided to punt on this, I guess, and tell you to explictly
make a new copy.

Now, this restriction doesn't occur in numarray. Resizing an array will
(maybe) make a new copy of the underlying memory. Then b in this case
will no longer point to a's data, but will be the owner of the old data.

[I say "maybe" as it depends on where the memory for a came from.]

|David M. Cooke                      http://arbutus.physics.mcmaster.ca/dmc/
|cookedm at physics.mcmaster.ca

More information about the NumPy-Discussion mailing list