元組 是 Python不可變序列,語法用圓括號 ()。與列表類似支援索引、切片、聯集,但建立後無法修改。這特性使其適合作為字典鍵、函數多返回值、固定結構資料載體。
# 多元素
t1 = ('physics', 'chemistry', 1997, 2000)
t2 = (1, 2, 3, 4, 5)
# 單元素:必須有逗號
t3 = (50,) # 元組
not_tuple = (50) # 整數 50
# 空元組
empty = ()
# 省略括號 (打包)
t4 = "a", "b", "c", "d"
print(type(t4)) #
# 解包
x, y = 1, 2 # 實際是 tuple 解包
t = ('physics', 'chemistry', 1997, 2000)
print(t[0]) # 'physics'
print(t[1:3]) # ('chemistry', 1997)
print(t[-1]) # 2000
print(t[:2]) # ('physics', 'chemistry')
# 巢狀元組
nested = (1, (2, 3), 4)
print(nested[1][0]) # 2
t = (1, 2, 3)
# t[0] = 10 # TypeError: 'tuple' object does not support item assignment
# 變通:建立新元組
t2 = t + (4, 5) # 聯集
t3 = t * 2 # 重複
t4 = t[:1] + (99,) + t[1:] # 切片重組
print(t2, t3, t4)
| 運算子 | 範例 | 結果 |
|---|---|---|
+ | (1,2) + (3,4) | (1,2,3,4) |
* | (1,2) * 3 | (1,2,1,2,1,2) |
in | 2 in (1,2,3) | True |
len() | len((1,2,3)) | 3 |
min/max | min((3,1,2)) | 1 |
index() | (1,2,3).index(2) | 1 |
count() | (1,2,1).count(1) | 2 |
# 基本解包
a, b, c = (1, 2, 3)
# 延伸解包 (Py3)
first, *middle, last = (1, 2, 3, 4, 5)
print(first, middle, last) # 1 [2, 3, 4] 5
# 函數多返回值 (實際回傳元組)
def divmod_custom(a, b):
return a // b, a % b
q, r = divmod_custom(10, 3)
print(q, r) # 3 1
# 交換變數
x, y = 10, 20
x, y = y, x # 建立臨時元組 (y, x) 再解包
t = (1, 2, 3)
del t
# print(t) # NameError: name 't' is not defined
# 無法刪除單一元素 (不可變)
# del t[0] # TypeError
L = ('spam', 'Spam', 'SPAM!')
# 索引: 0 1 2
# 負索引:-3 -2 -1
# 切片 L[1:3] -> ('Spam', 'SPAM!')
# 切片 L[-2:] -> ('Spam', 'SPAM!')
# 逗號才是元組標誌,括號僅為分組/優先序
print('abc', -4.24e93, 18+6.6j, 'xyz') # 印出 4 個值
x, y = 1, 2 # 右側是隱式元組 (1, 2)
| 場景 | 推薦 | 理由 |
|---|---|---|
| 需修改/增刪元素 | 列表 | 可變 |
| 固定結構資料 (座標、RGB、記錄) | 元組 | 不可變、語意明確、可做 dict key |
| 函數回傳多值 | 元組 | 慣用、解包方便 |
| 大量同質資料、頻繁迭代 | 列表 | 記憶體略小、方法豐富 |
| 需做字典鍵 / 集合元素 | 元組 | 可雜湊 |
元組的不可變性不是限制,而是契約:承諾這組資料結構固定,讓程式碼更安全、更易推理。