tuple 元組變數

Python 基礎: tuple 元組變數

list 串列 功能一樣,但資料不能被修改

List 串列與 Tuple 元組差異

差異 List 串列 Tuple 元組
內容 內容可改變,新增與刪除 內容不可異動
執行速度 較慢 較快
安全 較低 較高,因為資料不會被異動

一般 tuple 元組

tuple_1 = (1, 2, 3, 4, 5)
print("tuple_1: ", tuple_1)
print("tuple_1[3]: ", tuple_1[3])
# tuple_1:  (1, 2, 3, 4, 5)
# tuple_1[3]:  4
tuple_1 = (1, "KJ", True)
print("tuple_1: ", tuple_1)
# tuple_1:  (1, 'KJ', True)

重複 tuple 元組

tuple_1 = (1, 2, 3)
tuple_2 = tuple_1 * 2
print("tuple_1: ", tuple_1)
print("tuple_2: ", tuple_2)

# tuple_1:  (1, 2, 3)
# tuple_2:  (1, 2, 3, 1, 2, 3)

取得 tuple 元組中間元素

tuple_1 = (1, 2, 3, 4, 5, 6, 7)
tuple_2 = tuple_1[2:5]
print("tuple_1: ", tuple_1)
print("tuple_2: ", tuple_2)

# tuple_1:  (1, 2, 3, 4, 5, 6, 7)
# tuple_2:  (3, 4, 5)

錯誤案例

無法修改

TypeError: ’tuple’ object does not support item assignment

tuple_1 = (1, 2, 3, 4, 5, 6, 7)
tuple_1[3] = 33

# TypeError: 'tuple' object does not support item assignment

無法刪除

TypeError: ’tuple’ object does not support item deletion

tuple_1 = (1, 2, 3, 4, 5, 6, 7)
del tuple_1[2:5]

# TypeError: 'tuple' object does not support item deletion

參考資料