>>> 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'
In [1]: x = (1, 2)
In [2]: x[0] = 3
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython console> in <module>()
TypeError: 'tuple' object does not support item assignment