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 元组是不可变的 - 那为什么我可以向它添加元素
基础教程推荐
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
