python列表是可变的,Python列表可变吗?

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?

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值