《python基础》tuple可以修改吗?---可以的

tuple修改

问题:可以修改tuple的值?
思考:如果修改了会报错吗?

第一种:a[2] += [6,7]

>>> a = (1,2,[3,4])
>>> a[2] += [6,7]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(1, 2, [3, 4, 6, 7])

第二种:a[2] = [5,9]

>>> a[2] = [5,9]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> a
(1, 2, [3, 4, 6, 7])

第三种:append,extend

>>> a[2].append(0)
>>> a
(1, 2, [3, 4, 6, 7, 0])
>>> a[2].extend([5,8])
>>> a
(1, 2, [3, 4, 6, 7, 0, 5, 8])

第四种:变量形式

>>> list = [1,2]
>>> t = (3,4,list)
>>> list += [5]
>>> t
(3, 4, [1, 2, 5])

解释上述原因:

以后再整理吧

发布了35 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_34358193/article/details/102594793
今日推荐