Why was p[:] designed to work differently in these two situations?

后端 未结 6 1177
感动是毒
感动是毒 2021-02-01 12:42
p = [1,2,3]
print(p) # [1, 2, 3]

q=p[:]  # supposed to do a shallow copy
q[0]=11
print(q) #[11, 2, 3] 
print(p) #[1, 2, 3] 
# above confirms that q is not p, and is a d         


        
6条回答
  •  失恋的感觉
    2021-02-01 13:03

    As others have stated; p[:] deletes all items in p; BUT will not affect q. To go into further detail the list docs refer to just this:

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

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

    So q=p[:] creates a (shallow) copy of p as a separate list but upon further inspection it does point to a completely separate location in memory.

    >>> p = [1,2,3]
    >>> q=p[:]
    >>> id(q)
    139646232329032
    >>> id(p)
    139646232627080
    

    This is explained better in the copy module:

    A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.

    Although the del statement is performed recursively on lists/slices:

    Deletion of a target list recursively deletes each target, from left to right.

    So if we use del p[:] we are deleting the contents of p by iterating over each element, whereas q is not altered as stated earlier, it references a separate list although having the same items:

    >>> del p[:]
    >>> p
    []
    >>> q
    [1, 2, 3]
    

    In fact this is also referenced in the list docs as well in the list.clear method:

    list.copy()

    Return a shallow copy of the list. Equivalent to a[:].

    list.clear()

    Remove all items from the list. Equivalent to del a[:].

提交回复
热议问题