Tuple的特性在於,它的元素是不可變的(immutable),一旦設定,就不能使用索引去修改。
>>> t1=1,2,3,4,5 #給Tuple賦值 >>> t1[0] #按照索引讀取Tuple元素 1 >>> u1=t1,(2,3,4,5,6)#tuple可以嵌套 >>> u1 ((1, 2, 3, 4, 5), (2, 3, 4, 5, 6)) >>> u1[1] (2, 3, 4, 5, 6) >>> u1[-1] (2, 3, 4, 5, 6) >>> u1=t1,(2,3,4,5,6),3 >>> u1 ((1, 2, 3, 4, 5), (2, 3, 4, 5, 6), 3) >>> list1=['we','the','north'] >>> list1 ['we', 'the', 'north'] >>> u1=t1,list1 >>> u1 ((1, 2, 3, 4, 5), ['we', 'the', 'north']) >>> list1[-1]='toronto'#元組內的元素是可變的,所以可以修改內部元素來更新元組 >>> u1 ((1, 2, 3, 4, 5), ['we', 'the', 'toronto']) >>> len(u1) 2 >>> myList = [1,2,3,4,5,6,7,8,9,10] >>> myTuple = (1,2,3,4,5,6,7,8,9,10) >>> myList=(2,)#初始化一個元素的時候,需要帶comma >>> myList (2,) >>> myList[0] 2 >>> myList[1] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: tuple index out of range >>> len(myList) 1