python元组是不可变的-为什么我要向其中添加元素 [英] python tuple is immutable - so why can I add elements to it

查看:196
本文介绍了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元组是不可变的-为什么我要向其中添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆