版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012698342/article/details/88719174
In [12]: t = (1, 2, [3, 4])
In [13]: t[2] += [5, 6]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-13-1dc9eac03230> in <module>()
----> 1 t[2] += [5, 6]
TypeError: 'tuple' object does not support item assignment
In [14]: t
Out[14]: (1, 2, [3, 4, 5, 6])
In [15]: t[2].extend([7, 8])
In [16]: t
Out[16]: (1, 2, [3, 4, 5, 6, 7, 8])
In [17]: t[2] = [9, 10]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-17-a0007ad8f0ae> in <module>()
----> 1 t[2] = [9, 10]
TypeError: 'tuple' object does not support item assignment
In [18]: t
Out[18]: (1, 2, [3, 4, 5, 6, 7, 8])
前一个例子是在python cookbook
面试后和同事讨论,发现了第二个例子
说明元组不可变检查的是赋值操作
最后一个例子说明,元组内部可变元素可通过+=或extend修改,但子元素地址不变,但不可以通过=指向另一个不同地址的元素