Python 列表是可变的吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24292174/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 04:23:07  来源:igfitidea点击:

Are Python Lists mutable?

pythonlistmutable

提问by amandi

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?

如果列表是可变的,那么为什么在更改列表 x 时它会给出 2 个内存地址?

回答by amandi

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

您没有改变(更改)x此行引用的列表对象:

x=[2,5,3]

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

相反,该行创建了一个新的列表对象,然后将变量重新分配x给它。因此,x现在引用新对象并id(x)给出与以前不同的数字:

>>> 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]
>>>

回答by Martijn Pieters

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

您创建了一个新的列表对象并将其绑定到相同的名称x. 您从未x改变一开始绑定到的现有列表对象。

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

Python 中的名称只是引用。赋值是将名称绑定到对象。当您x再次分配给时,您将该引用指向一个不同的对象。在您的代码中,您只需创建一个全新的列表对象,然后重新绑定x到该新对象。

If you want to mutatea 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.

我们更改了列表对象(对其进行了变异),但该id()列表对象的 没有改变。它仍然是同一个列表对象。

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

或许 Ned Batchelder 关于 Python 名称和绑定的出色演示会有所帮助:关于 Python 名称和值的事实和神话

回答by timgeb

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

您不是在改变列表,而是在创建一个新列表并将其分配给 name x。这就是为什么id给你不同的输出。您的第一个列表已经消失,将被垃圾收集(除非在某处有另一个引用)。