我知道Slicing lists does not generate copies of the objects in the list; it just copies the references to them.
但如果是这样,那为什么这行不通呢?
l = [1, 2, 3]
# Attempting to modify the element at index 1
l[0:2][-1] = 10
# but the attempt fails. The original list is unchanged
l
> [1, 2, 3]
不应该
l[0:2][-1]
指向原始列表索引 1 处的元素?
最佳答案
切片 list
返回一个新的浅拷贝 list
目的。虽然您没有对原始列表的项目进行深度复制是正确的,但结果是一个全新的 list
区别于原版。
见 Python 3 tutorial :
All slice operations return a new list containing the requested elements. This means that the following slice returns a shallow copy of the list:
>>> squares = [1, 4, 9, 16, 25] >>> squares[:] [1, 4, 9, 16, 25]
考虑
>>> squares[:] is squares
False
关于python - 如果Python切片复制引用,为什么我不能用它来修改原始列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61580214/