So what's happening here?

Todd toddrjen at gmail.com
Fri Jun 5 08:55:11 EDT 2015


On Fri, Jun 5, 2015 at 2:46 PM, Paul Appleby <pap at nowhere.invalid> 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])
>
>
Numpy arrays are not lists, they are numpy arrays. They are two different
data types with different behaviors.  In lists, slicing is a copy.  In
numpy arrays, it is a view (a data structure representing some part of
another data structure).  You need to explicitly copy the numpy array using
the "copy" method to get a copy rather than a view:

>>> a = numpy.array([1,2,3])
>>> b = a.copy()
>>> a is b
False
>>> b[1] = 9
>>> a
array([1, 2, 3])

Here is how it works with lists:

>>> a = [1,2,3]
>>> b = a[:]
>>> a is b
False
>>> b[1] = 9
>>> a
[1, 2, 3]
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150605/274cfcc4/attachment.html>


More information about the Python-list mailing list