python元组不可变原理_Python中的元组真的不可变吗?

One question that I faced today, which actually tested the immutability of the tuples in Python:

Interviewer: Are tuples immutable in Python?

Me: Yes

Interviewer: So what does print(t1) here print?

t1 = (4, 5)

t1 = t1 + (91, 10)

print(t1)

Me: (4, 5, 91, 10)

Interviewer: How does immutability of tuple then define this behavior?

Me: It's got nothing to do with immutability, t1 label is referring to a new tuple.

Interviewer:

>>> t = (1, 2, [3, 4])

>>> t[2] += [5, 6]

What will happen next?

Me: TypeError is raised

Interviewer: What will be the value of t be after that?

Me: (1, 2, [3, 4]) or (1, 2, [3, 4, 5, 6]) maybe, not sure

Interviewer: What made you think the value will change to (1, 2, [3, 4, 5, 6]) and what will happen if I write

>>> t[2] = t[2] + [5, 6]

will t2 still be (1, 2, [3, 4, 5, 6]) after this operation?

解决方案

Even though the tuples are immutable, the object inside it can be mutuable

Since in >>> t = (1, 2, [3, 4]) the list is mutable so you can change the list value with Augmented assignment. += but then the exception is raised.

here the t[2] list is modified as you can see

t =(1,2,[3,4])

>>> id(t[2])

38073768

>>> t[2] += [5,6]

Traceback (most recent call last):

File "", line 1, in

TypeError: 'tuple' object does not support item assignment

>>> t[2]

[3, 4, 5, 6]

>>> id(t[2])

38073768

As you can see the t[2] id never gets changed.

As for the second case: t[2] = t[2] + [5,6] - it creates a new list and then assign it to t[2]

>>> li = [1,2]

>>> id(li)

38036304

>>> li = li + [3,4]

>>> id(li)

38074368

>>> li += [5,6]

>>> id(li)

38074368

As you can see List = list + [] is a new list with a different id. and as the tuple is immutable t[2] doesn't get assigned to a new object in the second case

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值