Mutability of lists in python

霸气de小男生 提交于 2019-12-11 05:34:11

问题


Example one: Changing the value that has been appended to b changes the value in the original list l

>>> l = [1 , 2, 3]
>>> b = []
>>> b.append(l)
>>> b[0].append(4)
>>> b
[[1, 2, 3, 4]]
>>> l
[1, 2, 3, 4]

Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.

>>> l1 = [1, 2, 3]
>>> ans = []
>>> ans.append(l1)
>>> ans
[[1, 2, 3]]
>>> l1 = [2, 3, 4]
>>> ans
[[1, 2, 3]]

I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?


回答1:


In your first example, l is a pointer, as well as b.

l is then appended to b, so b[0] now refers to the pointer.

Next, you append 4 to b[0], which is the same thing as l, so 4 is added to both b[0] and l.


In your second example, ans contains the pointer of l1, just like b contained the pointer of l

Then, you changed l1 itself by assigning it to a different array, so l1 changed but ans[0] did not.


The biggest takeaway from this is that append just changes the list, and the pointer remains the same. But when you set a variable to a different list, the pointer changes.




回答2:


You are not mutating l1. You are assigning a new object to the same name, which makes that name point to a new object. You are moving a label, not modifying an object. The only remaining reference to the list that l1 used to point to is now ans[0].




回答3:


Replace

>>> l1 = [2, 3, 4]

with

>>> l1[:] = [2, 3, 4]

That will not assign a new list to l1.



来源:https://stackoverflow.com/questions/39432396/mutability-of-lists-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!