当切片列表“副本”的值被覆盖时,原始列表不会改变。为什么?(Python)

Spa*_*iel 0 python immutability python-3.x

我来自 R,正在尝试更好地掌握可变性。下面是代码,我认为我理解其中的前两部分(请参阅评论)。我不明白第三部分。

#1. Refering to same instance with two variable names
listOrig = [i for i in range(1001, 1011)]
listCopy = listOrig
listOrig[0]=999
listOrig == listCopy #Returns True, because both variable names actually refer
#to the same instance, ergo still containing the same values
listOrig[0] is listCopy[0] #Same instance 999, the id is also the same as a 
#consequence

#2. Refering to same part of original list through slicing
listSlice = listOrig[0:5] 
listOrig[0] is listSlice[0] #Returns True, analogous to above
a = 999
listOrig[0] == a #True because it's the same value or number
listOrig[0] is a #False because they are different instances with different IDs
  
#3. WHAT I DO NOT UNDERSTAND: changing the sliced copy does not affect the original list
listOrig
listSlice
listSlice[0] = 1001
listOrig[0] is listSlice[0] #Different number, thus also obviously different ID
Run Code Online (Sandbox Code Playgroud)

khe*_*ood 5

我将发布一个答案只是因为我认为用图表可以更好地解释这一点。

假设您创建一个list_1包含数字 1、2 和 3 的列表。

list_1 = [1,2,3]
Run Code Online (Sandbox Code Playgroud)

列表_1

然后将该列表分配给一个新变量。

list_2 = list_1
Run Code Online (Sandbox Code Playgroud)

这是对同一原始列表的另一个引用。

列表_2

或者,假设您从清单中取出一部分。

list_3 = list_1[:]
Run Code Online (Sandbox Code Playgroud)

这是一个新列表,其中包含对相同对象的引用。

列表_3

因此,如果您在新列表中重新分配元素,则不会影响原始列表。

list_3[0] = 4
Run Code Online (Sandbox Code Playgroud)

已更改列表_3