3.3. 元组简介

元组是不可变的列表。元组一旦创建就无法以任何方式更改。

示例 3.15. 定义元组

>>> t = ("a", "b", "mpilgrim", "z", "example") 1
>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t[0]                                       2
'a'
>>> t[-1]                                      3
'example'
>>> t[1:3]                                     4
('b', 'mpilgrim')
1 元组的定义方式与列表相同,只是整个元素集用圆括号括起来,而不是方括号。
2 元组的元素具有定义的顺序,就像列表一样。元组索引是从零开始的,就像列表一样,所以非空元组的第一个元素始终是 t[0]
3 负索引从元组的末尾开始计数,就像列表一样。
4 切片也适用,就像列表一样。请注意,切片列表时,会得到一个新列表;切片元组时,会得到一个新元组。

示例 3.16. 元组没有方法

>>> t
('a', 'b', 'mpilgrim', 'z', 'example')
>>> t.append("new")    1
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'append'
>>> t.remove("z")      2
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'remove'
>>> t.index("example") 3
Traceback (innermost last):
  File "<interactive input>", line 1, in ?
AttributeError: 'tuple' object has no attribute 'index'
>>> "z" in t           4
True
1 您不能向元组添加元素。元组没有 appendextend 方法。
2 您不能从元组中删除元素。元组没有 removepop 方法。
3 您不能在元组中查找元素。元组没有 index 方法。
4 但是,您可以使用 in 来查看元组中是否存在某个元素。

那么元组有什么用呢?

Note
元组可以转换为列表,反之亦然。内置的 tuple 函数接受一个列表并返回具有相同元素的元组,而 list 函数接受一个元组并返回一个列表。实际上,tuple 冻结列表,而 list 解冻元组。

元组的进一步阅读