![](/img/trans.png)
[英]Why does the content of a tuple changes when I append to a list inside of it but does not change when I update a variable?
[英]Why does tuple consisting of list elements changes when list gets updated
我知道元組是不可變的。 但是我不明白為什么元組值在以下代碼中會發生變化。 我正在運行python 2.7
>>> k = [3,4]
>>> my_tuple = (k,k)
>>> my_tuple
([3, 4], [3, 4])
>>> k.append(20)
>>> my_tuple
([3, 4, 20], [3, 4, 20])
>>>
我期待my_tuple是'([3,4],[3,4])',而不是([3,4,20],[3,4,20])
元組是不可變的。 這並不意味着他們的內容必然是不可改變的。 元組不會“凍結”您放入其中的任何內容的副本; 它只是持有對象的引用。 如果你的元組包含可變對象,你可以像往常一樣改變它們。
元組是不可變的,但元組內的列表是可變的
您不能將新對象添加到元組,但如果它們是可變的,您可以添加到元組內的對象。 你沒有改變你正在改變存儲在元組中的元素的元組。
如果你試圖實際改變元組本身,你會收到一個錯誤:
In [12]: k = [3,4]
In [13]: my_tuple = (k,k)
In [14]: my_tuple[0] = [1,2,3]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-14-c170b930bb12> in <module>()
----> 1 my_tuple[0] = [1,2,3]
TypeError: 'tuple' object does not support item assignment
當您附加到列表時,您沒有更改元組所包含的對象,而只是改變了一個可變對象:
In [15]: id(my_tuple[0])
Out[15]: 140625164882288
In [16]: my_tuple[0].append(20)
In [17]: id(my_tuple[0])
Out[17]: 140625164882288
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.