python - 如果Python切片复制引用,为什么我不能用它来修改原始列表?

标签 python list reference

我知道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/

相关文章:

类和实例变量的 Python 引用

python - 如何在 TensorFlow 中取消引用 _ref 张量类型?

c++ - 有没有更好的方法来初始化引用成员以引用同一个类中的另一个成员

python - 如何在 Python 中查找所有子模块?

c - 为什么 BSD 在链表条目中使用双指针?

Python:查找列表中的所有元素是否都相同,除了恰好 2 个数字

java - Groovy/Grails 包含小写字母

javascript - 我无法在谷歌图表的代码 javascript 中获取 json 数据(项目 Python Hello Dashboard 示例)

python - Pandas :替换缺失的数据框值/条件计算:fillna

python - 如何根据 Pandas 中另一行中的值组合一行中的值