Does [:] slice only make shallow copy of a list?

前端 未结 5 1330
Happy的楠姐
Happy的楠姐 2020-12-10 08:41

I have experienced peculiar bugs from this [:] copy.

The docs say [:] makes only a shallow copy but seems:

a = [1,2,3]
id(         


        
5条回答
  •  佛祖请我去吃肉
    2020-12-10 09:40

    Numpy answer:

    Arrays in numpy are views/indexes on a backing storage.

    You can copy the view, without copying the backing storage...

    a=numpy.array([1,2,3,4])
    b=a[:] # copy of the array ("view" or "index"), not the storage
    b.shape=(2,2)
    print a
    # [1 2 3 4]
    print b
    # [[1 2]
    #  [3 4]]
    b *= 2
    print a
    # [2 4 6 8]
    print b
    # [[2 4]
    #  [6 8]]
    

    See how changing b affected a? Yet they still have a different shape. Consider them to be views of the data; and the b=a[:] line copied just this view. I could even modify the shape of b. Because it is just an index to the data, that says where columns and rows are located in memory.

    If you want a copy of the backing storage in numpy, use a.copy().

提交回复
热议问题