python元组中添加元素_python元组是不可变的-为什么我要向其中添加元素

I've been using Python for some time already and today while reading the following code snippet:

>>> a = (1,2)

>>> a += (3,4)

>>> a

(1, 2, 3, 4)

I asked myself a question: how come python tuples are immutable and I can use an += operator on them (or, more generally, why can I modify a tuple)? And I couldn't answer myself.

I get the idea of immutability, and, although they're not as popular as lists, tuples are useful in python. But being immutable and being able to modify length seems contradictory to me...

解决方案

5 is immutable, too. When you have an immutable data structure, a += b is equivalent to a = a + b, so a new number, tuple or whatever is created.

When doing this with mutable structures, the structure is changed.

Example:

>>> tup = (1, 2, 3)

>>> id(tup)

140153476307856

>>> tup += (4, 5)

>>> id(tup)

140153479825840

See how the id changed? That means it's a different object.

Now with a list, which is mutable:

>>> lst = [1, 2, 3]

>>> id(lst)

140153476247704

>>> lst += [4, 5]

>>> id(lst)

140153476247704

The id says the same.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值