python的Tuple(元组)的几点注意事项

时间:2021-09-14 02:34:14

1,Tuple(元组)里面的元素不支持复制修改。

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

2,Tuple(元组)可以切片,也可以拼接。

>>> a = (1,2,3,4,5)
>>> a[2:4]
(3, 4)
>>> a + (6,7,8)
(1, 2, 3, 4, 5, 6, 7, 8)

3,Tuple(元组)里面的元素如果是list或dict这些可以修改的值,那这些值里面的内容可以修改。

>>> b = (1,[2,3,4],5,6)
>>> b[1][1] = 7    # b[1] 相当于是列表[2,3,4]
>>> b
(1, [2, 7, 4], 5, 6)