列表是可变的,这意味着您可以更改其内容:
>>> x = [1,2]
>>> x.append(3)
>>> x
[1, 2, 3]
而元组不是:
>>> x = (1,2)
>>> x
(1, 2)
>>> x.append(3)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'tuple' object has no attribute 'append'
另一个主要区别是元组是可散列的,这意味着您可以将其用作字典的键等.例如:
>>> x = (1,2)
>>> y = [1,2]
>>> z = {}
>>> z[x] = 3
>>> z
{(1, 2): 3}
>>> z[y] = 4
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
请注意,正如许多人指出的,可以将元组添加到一起.例如:
>>> x = (1,2)
>>> x += (3,)
>>> x
(1, 2, 3)
然而,this does not mean tuples are mutable.在上面的示例中,通过将两个元组作为参数相加来构造new元组.不修改原始元组.要演示这一点,请考虑以下内容:
>>> x = (1,2)
>>> y = x
>>> x += (3,)
>>> x
(1, 2, 3)
>>> y
(1, 2)
然而,如果你用一个列表来构建这个相同的例子,y
也会被更新:
>>> x = [1, 2]
>>> y = x
>>> x += [3]
>>> x
[1, 2, 3]
>>> y
[1, 2, 3]