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

后端 未结 6 1192
感动是毒
感动是毒 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 12:59

    del on iterator is just a call to __delitem__ with index as argument. Just like parenthesis call [n] is a call to __getitem__ method on iterator instance with index n.

    So when you call p[:] you are creating a sequence of items, and when you call del p[:] you map that del/__delitem__ to every item in that sequence.

提交回复
热议问题