Python list slice as shallow copy

廉价感情. 提交于 2021-02-11 06:20:04

问题


foo = [1, 2, 3]  
foo[:][0] = 5

foo doesn't change, also:

import copy  
foo = [1, 2, 3]   
boo = copy.copy(foo)  
boo[0] = 5

Again, foo[0] stays the same.

Why? The shallow copy creates new list, but shouldn't boo[0]/boo[1]/boo[2] point to the same objects as foo[0]/foo[1]/foo[2]?


回答1:


boo[0] does point to the same object as foo[0]. But doing boo[0] = 5 does not modify the object referred to by boo[0]; it modifies the object referred to by boo.

Assigning to an element of a list modifies the list by changing what that element "points to". It has no effect on the object that is pointed to.



来源:https://stackoverflow.com/questions/34231577/python-list-slice-as-shallow-copy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!