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

后端 未结 6 1332
感动是毒
感动是毒 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:02

    I'm not sure if you want this sort of answer. In words, for p[:], it means to "iterate through all elements of p". If you use it in

    q=p[:]
    

    Then it can be read as "iterate with all elements of p and set it to q". On the other hand, using

    q=p
    

    Just means, "assign the address of p to q" or "make q a pointer to p" which is confusing if you came from other languages that handles pointers individually.

    Therefore, using it in del, like

    del p[:]
    

    Just means "delete all elements of p".

    Hope this helps.

提交回复
热议问题