问题描述
有人可以解释为什么整数示例导致x和y的值不同,而列表示例导致x和y是同一对象的原因吗?
Can someone explain why the example with integers results in different values for x and y and the example with the list results in x and y being the same object?
x = 42
y = x
x = x + 1
print x # 43
print y # 42
x = [ 1, 2, 3 ]
y = x
x[0] = 4
print x # [4, 2, 3]
print y # [4, 2, 3]
x is y # True
推荐答案
因为整数是不可变的,而列表是可变的.您可以从语法中看到.在x = x + 1
中,您实际上是在为x
分配一个新值(在LHS上是单独的).在x[0] = 4
中,您要在列表上调用索引运算符并为其指定一个参数-它实际上等效于x.__setitem__(0, 4)
,这显然是在更改原始对象,而不是创建新对象.
Because integers are immutable, while list are mutable. You can see from the syntax. In x = x + 1
you are actually assigning a new value to x
(it is alone on the LHS). In x[0] = 4
, you're calling the index operator on the list and giving it a parameter - it's actually equivalent to x.__setitem__(0, 4)
, which is obviously changing the original object, not creating a new one.
这篇关于Python参考的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!