元组内部的值只是对列表的引用,如果我更改列表中的值,一切都仍然有序,对吧?我想确保如果我这样做,我就不会开始遇到令人困惑的错误。
答案 0 :(得分:11)
元组是不可变的,你可能不会改变它们的内容。
有一个清单
>>> x = [1,2,3]
>>> x[0] = 5
>>> x
[5, 2, 3]
使用元组
>>> y = tuple([1,2,3])
>>> y
(1, 2, 3)
>>> y[0] = 5 # Not allowed!
Traceback (most recent call last):
File "<pyshell#20>", line 1, in <module>
y[0] = 5
TypeError: 'tuple' object does not support item assignment
但如果我理解你的问题,说你有
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> t = (a,b)
>>> t
([1, 2, 3], [4, 5, 6])
允许 将内部列表修改为
>>> t[0][0] = 5
>>> t
([5, 2, 3], [4, 5, 6])
答案 1 :(得分:6)
元组是不可变的 - 你不能改变它们的结构
>>> a = []
>>> tup = (a,)
>>> tup[0] is a # tup stores the reference to a
True
>>> tup[0] = a # ... but you can't re-assign it later
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
>>> tup[0] = 'string' # ... same for all other objects
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment
或大小
>>> del tup[0] # Nuh uh
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item deletion
>>> id(tup)
139763805156632
>>> tup += ('something',) # works, because it creates a new tuple object:
>>> id(tup) # ... the id is different
139763805150344
创建它们之后。
另一方面,存储在元组中的可变对象不会失去其可变性,例如您仍然可以使用列表方法修改内部列表:
>>> a = []
>>> b, c = (a,), (a,) # references to a, not copies of a
>>> b[0].append(1)
>>> b
([1],)
>>> c
([1],)
元组可以存储任何类型的对象,尽管包含列表(或任何其他可变对象)的元组不是hashable:
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
上述行为确实会导致混淆错误。