[Numpy-discussion] array copy-to-self and views

Zachary Pincus zpincus@stanford....
Thu Feb 1 02:28:17 CST 2007


Hello folks,

I recently was trying to write code to modify an array in-place (so  
as not to invalidate any references to that array) via the standard  
python idiom for lists, e.g.:

a[:] = numpy.flipud(a)

Now, flipud returns a view on 'a', so assigning that to 'a[:]'  
provides pretty strange results as the buffer that is being read (the  
view) is simultaneously modified. Here is an example:

In [2]: a = numpy.arange(10).reshape((5,2))
In [3]: a
Out[3]:
array([[0, 1],
        [2, 3],
        [4, 5],
        [6, 7],
        [8, 9]])
In [4]: numpy.flipud(a)
Out[4]:
array([[8, 9],
        [6, 7],
        [4, 5],
        [2, 3],
        [0, 1]])
In [5]: a[:] = numpy.flipud(a)
In [6]: a
Out[6]:
array([[8, 9],
        [6, 7],
        [4, 5],
        [6, 7],
        [8, 9]])

A question, then: Does this represent a bug? Or perhaps there is a  
better idiom for modifying an array in-place than 'a[:] = ...'? Or is  
incumbent on the user to ensure that any time an array is directly  
modified, that the modifying array is not a view of the original array?

Thanks for any thoughts,

Zach Pincus

Program in Biomedical Informatics and Department of Biochemistry
Stanford University School of Medicine



More information about the Numpy-discussion mailing list