问题描述
在阅读以下代码片段时,我已经使用 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 元组是不可变的 - 那为什么我可以向它添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!