Tuple 與序列
Python中有三種序列(Squence)類型包括: lists、tuples、range物件,其中今天要介紹的tuple為不可變(immutable)的序列類型,語法為小括號()及逗點如下:
建立一個 tuple
#%% Create a tuple
a = 12345, 54321, "Hello"
print("a:", a)
a = (12345, 54321, "Hello")
print("a:", a)
Tuple 是不可變型別
因為tuple為不可變型別,不可以改變其中元素的值
#%% Tuple is immutable
a[0] = 88888
print(a)
TypeError: 'tuple' object does not support item assignment
結果顯示錯誤報警,說明 tuple 不支援給其中的元素賦值,得知 tuple 為不可變型別
list運算與操作
操作 | 描述 |
---|---|
(1,2,3)+(4,5,6) | 組合 |
(1,2,3)*3 | 重複 |
3 in (1,2,3) | 判斷列表內是否有該元素 |
3 not in (1,2,3) | 判斷列表內是否無該元素 |
索引取值
tuple也可以用index索引存取列表內每個元素的值進行列表的操作
Index and slice [開始:結束:step]
操作 | 描述 |
---|---|
s[i] | i th item of s , origin 0 |
s[i:j] | slice of s from i to j |
s[i:j:k] | slice of s from i to j with step k |
Tuple 的序列封裝與拆封 packing and unpacking
#%% Tuple packing and unpacking
a = 12345, 54321, "Hello" # packing
x, y, z = a # unpacking
print(f"x, y, z: {x}, {y}, {z}")
x, y = a # wrong unpacking
x, y, z, d = a # wrong unpacking
ValueError: too many values to unpack (expected 2)
ValueError: not enough values to unpack (expected 4, got 3)
拆封元素個數必須與 tuple 中元素個數一致,否則報警處理XDD
刪除列表元素
由於tuple為不可變型別(immutable),不能改變元素的值,所以不支援del操作
s = (-1, 1, 66.25, 333, 333, 1234.5)
del s[0]
TypeError: 'tuple' object doesn't support item deletion
Tuples and Sequences
https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences