On Fri, Jun 5, 2015 at 2:46 PM, Paul Appleby <pap@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]
-- https://mail.python.org/mailman/listinfo/python-list