如果可以添加元组,元组如何不可变 (a += (3,4)) [英] How is a tuple immutable if you can add to it (a += (3,4))

查看:33
本文介绍了如果可以添加元组,元组如何不可变 (a += (3,4))的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<预><代码>>>>a = (1,2)>>>a += (3,4)>>>一种(1, 2, 3, 4)>>>

并带有列表:

<预><代码>>>>b = [1,2]>>>b += [3,4]>>>乙[1, 2, 3, 4]>>>

由于元组是不可变的,而列表是可变的,我们如何解释这种行为?

解决方案

Tuple 是不可变类型,意味着你不能改变存储在变量 a 中的值.例如,执行以下操作

<预><代码>>>>a = (1, 2)>>>[0] = 3

抛出错误TypeError: 'tuple' object does not support item assignment.

另一方面,对于列表,

<预><代码>>>>a = [1, 2]>>>[0] = 3

这是完全有效的,因为它是可变的.

您正在做的是为变量名称重新分配值.

a = a + (3, 4) 只是将两者连接起来并将其重新分配给变量 a.您实际上并未更改元组的值.

例如,string 是不可变的,因此,

<预><代码>>>>名称 = "福">>>名称[0] ='o'

抛出与上述类似的错误.但是,以下是重新分配并且完全有效.

<预><代码>>>>名称=名称+酒吧">>>姓名'福吧'

它只是进行串联.

>>> a = (1,2)
>>> a += (3,4)
>>> a
(1, 2, 3, 4)
>>> 

and with a list:

>>> b = [1,2]
>>> b += [3,4]
>>> b
[1, 2, 3, 4]
>>> 

As a tuple is immutable and list is mutable, how can we explain the behaviour?

解决方案

Tuple is of immutable type, means that you cannot change the values stored in the variable a. For example, doing the following

>>> a = (1, 2)
>>> a[0] = 3

throws up the error TypeError: 'tuple' object does not support item assignment.

On the other hand, for a list,

>>> a = [1, 2]
>>> a[0] = 3

this is perfectly valid because it is mutable.

What you are doing is reassigning values to the variable names.

a = a + (3, 4) which just concatenates the two and reassigns it to the variable a. You are not actually changing the value of the tuple.

For example, string is immutable, and hence,

>>> name = "Foo"
>>> name[0] ='o' 

throws up a similar error as above. But, the following is a reassignment and completely valid.

>>> name = name + " Bar"
>>> name
'Foo Bar'

and it just does a concatenation.

这篇关于如果可以添加元组,元组如何不可变 (a += (3,4))的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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