如果在 Python 中我将一个列表放在一个元组中,我可以安全地更改该列表的内容吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26262813/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
If in Python I put a list inside a tuple, can I safely change the contents of that list?
提问by Sophie
The value inside the tuple is simply a reference to a list, and if I change the values in the list everything is still in order, right? I want to make sure that if I do this I won't start running into confusing errors.
元组中的值只是对列表的引用,如果我更改列表中的值,一切仍然正常,对吗?我想确保如果我这样做,我不会开始遇到令人困惑的错误。
采纳答案by Cory Kramer
Tuples are immutable, you may not change their contents.
元组是不可变的,你不能改变它们的内容。
With a list
有清单
>>> x = [1,2,3]
>>> x[0] = 5
>>> x
[5, 2, 3]
With a tuple
用元组
>>> 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
But if I understand your question, say you have
但如果我理解你的问题,说你有
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> t = (a,b)
>>> t
([1, 2, 3], [4, 5, 6])
You are allowedto modify the internal lists as
您可以将内部列表修改为
>>> t[0][0] = 5
>>> t
([5, 2, 3], [4, 5, 6])
回答by vaultah
Tuples are immutable - you can't change their structure
元组是不可变的——你不能改变它们的结构
>>> 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
or size
或大小
>>> 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
after you create them.
创建它们之后。
On the other hand, mutable objects stored in a tuple do not lose their mutability e.g. you can still modify inner lists using list methods:
另一方面,存储在元组中的可变对象不会失去其可变性,例如您仍然可以使用列表方法修改内部列表:
>>> a = []
>>> b, c = (a,), (a,) # references to a, not copies of a
>>> b[0].append(1)
>>> b
([1],)
>>> c
([1],)
Tuples can store any kind of object, although tuples that contain lists (or any other mutable objects) are not hashable:
元组可以存储任何类型的对象,尽管包含列表(或任何其他可变对象)的元组是不可散列的:
>>> hash(b)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
The behaviour demonstrated above can indeed lead to confusing errors.
上面演示的行为确实会导致令人困惑的错误。

