If Python slice copy the reference, why can't I use it to modify the original list?

前端 未结 3 637
野性不改
野性不改 2021-01-21 03:48

I know that Slicing lists does not generate copies of the objects in the list; it just copies the references to them.

But if that\'s the case, then why doesn\'t this wor

3条回答
  •  -上瘾入骨i
    2021-01-21 04:42

    Slicing a list returns a new shallowly-copied list object. While you are correct that it does not deep-copy the original list's items, the result is a brand new list distinct from the original.

    See the Python 3 tutorial:

    All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:

    >>> squares = [1, 4, 9, 16, 25]
    >>> squares[:]
    [1, 4, 9, 16, 25]
    

    Consider

    >>> squares[:] is squares
    False
    

提交回复
热议问题