python tuple is immutable - so why can I add elements to it(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)
我问自己一个问题:为什么 python 元组是不可变的,我可以对它们使用 +=
运算符(或者,更一般地说,为什么我可以修改元组)?而我自己也无法回答.
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.
我理解了不变性,虽然它们不像列表那样流行,但元组在 python 中很有用.但是不可变并且能够修改长度对我来说似乎是矛盾的......
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
也是不可变的.当你有一个不可变的数据结构时,a += b
等价于 a = a + b
,所以会创建一个新的数字、元组或其他任何东西.
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.
例子:
>>> tup = (1, 2, 3)
>>> id(tup)
140153476307856
>>> tup += (4, 5)
>>> id(tup)
140153479825840
看看 id
是如何变化的?这意味着它是一个不同的对象.
See how the id
changed? That means it's a different object.
现在有了一个可变的list
:
>>> lst = [1, 2, 3]
>>> id(lst)
140153476247704
>>> lst += [4, 5]
>>> id(lst)
140153476247704
id
也一样.
这篇关于python 元组是不可变的 - 那为什么我可以向它添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:python 元组是不可变的 - 那为什么我可以向它添加元素


基础教程推荐
- 用于分类数据的跳跃记号标签 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 筛选NumPy数组 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01