DAY 11
0

## Python - tuple 元組

Tuple 與序列
Python中有三種序列(Squence)類型包括: lists、tuples、range物件，其中今天要介紹的tuple為不可變(immutable)的序列類型，語法為小括號()及逗點如下：

``````#%% Create a tuple
a = 12345, 54321, "Hello"
print("a:", a)
a = (12345, 54321, "Hello")
print("a:", a)
``````

Tuple 是不可變型別

``````#%% Tuple is immutable
a[0] = 88888
print(a)

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

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)
``````

``````s = (-1, 1, 66.25, 333, 333, 1234.5)
del s[0]

TypeError: 'tuple' object doesn't support item deletion
``````

## Reference

Tuples and Sequences
https://docs.python.org/3/tutorial/datastructures.html#tuples-and-sequences

30天學會Python30