Are Python Lists mutable?

情到浓时终转凉″ 提交于 2019-11-27 08:06:14

问题


When I type following code,

x=[1,2,4]
print(x)
print("x",id(x))
x=[2,5,3]
print(x)
print("x",id(x))

it gives the output as

[1, 2, 4]
x 47606160
[2, 5, 3]
x 47578768

If lists are mutable then why it give 2 memory address when changing the list x?


回答1:


You did not mutate (change) the list object referenced by x with this line:

x=[2,5,3]

Instead, that line creates a new list object and then reassigns the variable x to it. So, x now references the new object and id(x) gives a different number than before:

>>> x=[1,2,4]  # x references the list object [1,2,4]
>>> x
[1, 2, 4]
>>> x=[2,5,3]  # x now references an entirely new list object [2,5,3]
>>> x
[2, 5, 3]
>>>



回答2:


You created a new list object and bound it to the same name, x. You never mutated the existing list object bound to x at the start.

Names in Python are just references. Assignment is binding a name to an object. When you assign to x again, you are pointing that reference to a different object. In your code, you simply created a whole new list object, then rebound x to that new object.

If you want to mutate a list, call methods on that object:

x.append(2)
x.extend([2, 3, 5])

or assign to indices or slices of the list:

x[2] = 42
x[:3] = [5, 6, 7]

Demo:

>>> x = [1, 2, 3]
>>> id(x)
4301563088
>>> x
[1, 2, 3]
>>> x[:2] = [42, 81]
>>> x
[42, 81, 3]
>>> id(x)
4301563088

We changed the list object (mutated it), but the id() of that list object did not change. It is still the same list object.

Perhaps this excellent presentation by Ned Batchelder on Python names and binding can help: Facts and myths about Python names and values.




回答3:


You are not mutating the list, you are creating a new list and assigning it to the name x. That's why id is giving you different outputs. Your first list is gone and will be garbage-collected (unless there's another reference to it somewhere).



来源:https://stackoverflow.com/questions/24292174/are-python-lists-mutable

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