全变量浅拷贝和切片部分拷贝的区别

Difference between full variable shallow copying and slice partial copying

据我了解,Python是一种传递对象引用语言,这意味着如果原始值是可变的,每个浅拷贝都会受到影响(反之亦然)。所以,像这样:

x = [1,2,3]
y = x
x.append(4)
print(y[-1]) -> 4

是数组可变性的预期结果。但是当我使用切片运算符进行浅拷贝时:

x = [1,2,3]
y = x[:]
x.append(4)
print(y[-1]) -> 3

为什么会发生这种行为?

id built-in 函数会有帮助。 is 运算符也是如此。

x = [1,2,3]
y = x
print(y == x) # True
print(y is x) # True
print(id(y) == id(x)) # True

所以都是真的。 x 和 y 具有相同的值,它们在内存中占用相同的space。

x = [1,2,3]
y = x[:]
print(y == x) # True
print(y is x) # False
print(id(y) == id(x)) # False

只有 == 运算符为真。 x 和 y 共享相同的值。但是,它们存在于两个不同的内存位置。