Python 中的元组是不可变的吗? [英] Are tuples in Python immutable?
本文介绍了Python 中的元组是不可变的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
它说
<块引用>元组一旦创建就不能以任何方式更改.
但是当我执行以下操作时:
t1=(4,5,8,2,3)t1=t1+(7,1)打印(t1)
元组正在更改为 (4, 5, 8, 2, 3, 7, 1)
;这是为什么?元组不可变"的真正含义是什么?
解决方案
是的,元组是不可变的;一旦创建,就无法更改.t1=t1+(7,1)
创建一个新元组并将其分配给名称t1
.它不会更改最初由该名称引用的元组对象.
演示:
<预><代码>>>>t = (1, 2, 3)>>>编号(t)4365928632>>>t = t + (4, 5)>>>编号(t)4354884624 #不同的id,不同的对象It says
A tuple can not be changed in any way once it is created.
But when I do the following:
t1=(4,5,8,2,3)
t1=t1+(7,1)
print(t1)
the tuple is changing to (4, 5, 8, 2, 3, 7, 1)
; why is that? What is really meant by "tuples are immutable"?
解决方案
Yes, tuples are immutable; once created, they cannot be changed. t1=t1+(7,1)
creates a new tuple and assigns it to the name t1
. It does not change the tuple object originally referenced by that name.
Demo:
>>> t = (1, 2, 3)
>>> id(t)
4365928632
>>> t = t + (4, 5)
>>> id(t)
4354884624 # different id, different object
这篇关于Python 中的元组是不可变的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文