So what's happening here?

Peter Otten __peter__ at web.de
Fri Jun 5 09:09:03 EDT 2015


Paul Appleby wrote:

> I saw somewhere on the net that you can copy a list with slicing. So
> what's happening when I try it with a numpy array?
> 
>>>> a = numpy.array([1,2,3])
>>>> b = a[:]
>>>> a is b
> False
>>>> b[1] = 9
>>>> a
> array([1, 9, 3])

Copy or view -- have a look under the hood:

>>> a = numpy.array([1,2,3])
>>> v = a.view()
>>> c = a.copy()
>>> s = a[:]
>>> a.flags["OWNDATA"]
True
>>> v.flags["OWNDATA"]
False
>>> c.flags["OWNDATA"]
True
>>> s.flags["OWNDATA"]
False

You only get a copy if you ask for one; slicing produces a view.




More information about the Python-list mailing list