For normal list in Python, slicing copies the references without copying underlying contents. (See the fact that`id(a[1])` and `id(b[0])` are identical below.)
>>> a = [1,2,3] >>> b = a[1:3] >>> a [1, 2, 3] >>> b [2, 3] >>> id(a[1]) 25231680 >>> id(b[0]) 25231680 >>> b[0] = 999 >>> a [1, 2, 3] >>> b [999, 3]
For numpy array, slicing doesn’t copy anything: it just returns a view of the original array. Therefore, changes made in the sliced array is essentially made in the original array.
>>> a = numpy.array([1,2,3]) >>> b = a[1:3] >>> a array([1, 2, 3]) >>> b array([2, 3]) >>> id(a[1]) 140093599322520 >>> id(b[0]) 140093599322520 >>> b[0]=999 >>> a array([ 1, 999, 3]) >>> b array([999, 3])
Refs:
http://stackoverflow.com/questions/5131538/slicing-a-list-in-python-without-generating-a-copy
http://stackoverflow.com/questions/3485475/can-i-create-a-view-on-a-python-list