问题
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