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

Christopher Barker Chris.Barker@noaa....
Thu Feb 1 14:12:34 CST 2007

Zachary Pincus wrote:
>>> I recently was trying to write code to modify an array in-place (so
>>> as not to invalidate any references to that array)
>> I'm not sure what this means exactly.
> Say one wants to keep two different variables referencing a single in- 
> memory list, as so:
> a = [1,2,3]
> b = a
> Now, if 'b' and 'a' go to live in different places (different class  
> instances or whatever) but we want 'b' and 'a' to always refer to the  
> same in-memory object, so that 'id(a) == id(b)', we need to make sure  
> to not assign a brand new list to either one.

OK, got it, but numpy arrays are not quite the same as lists, there is 
the additional complication that two different array objects can share 
the same data:

 >>> b = a[:]
 >>> a = N.ones((5,))
 >>> b = a[:]
 >>> a is b
 >>> a[2] = 5
 >>> a
array([ 1.,  1.,  5.,  1.,  1.])
 >>> b
array([ 1.,  1.,  5.,  1.,  1.])

This is very useful, but can be tricky. In a way, it's like a nested list:
 >>> a = [[1,2,3,4]]
 >>> b = [a[0]]
 >>> a is b
 >>> a[0][2] = 5
 >>> a
[[1, 2, 5, 4]]
 >>> b
[[1, 2, 5, 4]]

hey! changing a changed b too!

So key is that in your case, it probably doesn't matter if a and b are 
the same object, as long as they share the same data, and having 
multiple arrays sharing the same data is a common idiom in numpy.

> That is, if we do something like 'a = [i + 1 for i in a]' then 'id 
> (a) != id(b)'. However, we can do 'a[:] = [i + 1 for i in a]' to  
> modify a in-place.

Ah, but at Travis pointed out, the difference is not in assignment or 
anything like that, but in the fact that a list comprehension produces a 
copy, which is analogous to :


In numpy, you DO need to be aware of when you are getting copies, and 
when you are getting views, and what the consequences are.

So really, the only "bug" here is in the docs -- they should make it 
clear whether a function returns a copy or a view.


Christopher Barker, Ph.D.

Emergency Response Division
NOAA/NOS/OR&R            (206) 526-6959   voice
7600 Sand Point Way NE   (206) 526-6329   fax
Seattle, WA  98115       (206) 526-6317   main reception


More information about the Numpy-discussion mailing list