[牛客试题] 元组的操作
题目
若 a = (1, 2, 3),下列哪些操作是合法的?
A a[1:-1]
B a*3
C a[2] = 4
D list(a)
题解
In [1]: a = (1, 2, 3)
In [2]: a[1:-1]
Out[2]: (2,)
In [3]: a*3
Out[3]: (1, 2, 3, 1, 2, 3, 1, 2, 3)
In [5]: a[2] = 4 # 元组为不可变对象,不可以赋值
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-fdddcd2211ce> in <module>()
----> 1 a[2] = 4
TypeError: 'tuple' object does not support item assignment
In [6]: list(a)
Out[6]: [1, 2, 3]
答案:A B D