Python列表可变吗? [英] Are Python Lists mutable?

查看:600
本文介绍了Python列表可变吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我输入以下代码时,

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

它给出的输出为

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

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

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

推荐答案

您创建了一个新列表对象,并将其绑定到相同的名称x.您永远不会从一开始就更改绑定到x的现有列表对象.

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.

Python中的名称只是参考.分配将名称绑定到对象.当您再次分配给x时,您就是将该引用指向另一个对象.在您的代码中,您仅创建了一个全新的列表对象,然后将x反弹到该新对象.

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]

演示:

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

我们更改了列表对象(对其进行了突变),但是该列表对象的id()并未更改.它仍然是相同的列表对象.

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

Ned Batchelder关于Python名称和绑定的出色介绍也许可以帮助您: 有关的事实和神话Python名称和值 .

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

这篇关于Python列表可变吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆