元组也是有序表,区别在于tuple一旦初始化后,就不能再改变,此处的不变时说,tuple的每个元素的指向永远不变。
In [58]: t = (2, 1) In [59]: t Out[59]: (2, 1) # 定义空的tuple In [60]: t = () In [61]: t Out[61]: () # 定义只有一个元素的tuple # 注意:定义时,是有逗号的,若没有的话,就是定义1这个数 In [62]: t = (1, ) In [63]: t Out[63]: (1,) # 若没有逗号,则得到的不是一个元组 In [91]: a = (1) In [92]: type(a) Out[92]: int
In [73]: a = [1, 2] In [74]: b = [3, 4] In [75]: c = ('A', a) In [76]: c Out[76]: ('A', [1, 2]) # tuple元素指向不能改变,所以报了异常 In [77]: c[0] = b -------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-77-5b8a7e0cb452> in <module>() ----> 1 c[0] = b TypeError: 'tuple' object does not support item assignment -------------------------------------------------------------------- # tuple中的list元素的内容可以改变 In [78]: c[1][1] = 3 In [79]: c Out[79]: ('A', [1, 3])